Flask Documentation (1.1.x) Release 1.1.4
Pallets
May 14, 2021
CONTENTS
1 User’s Guide 3 1.1 Foreword...... 3 1.2 Foreword for Experienced Programmers...... 4 1.3 Installation...... 4 1.4 Quickstart...... 7 1.5 Tutorial...... 21 1.6 Templates...... 57 1.7 Testing Flask Applications...... 60 1.8 Application Errors...... 67 1.9 Debugging Application Errors...... 70 1.10 Logging...... 71 1.11 Configuration Handling...... 74 1.12 Signals...... 83 1.13 Pluggable Views...... 86 1.14 The Application Context...... 89 1.15 The Request Context...... 91 1.16 Modular Applications with Blueprints...... 95 1.17 Extensions...... 99 1.18 Command Line Interface...... 100 1.19 Development Server...... 108 1.20 Working with the Shell...... 108 1.21 Patterns for Flask...... 110 1.22 Deployment Options...... 156 1.23 Becoming Big...... 167
2 API Reference 169 2.1 API...... 169
3 Additional Notes 233 3.1 Design Decisions in Flask...... 233 3.2 HTML/XHTML FAQ...... 235 3.3 Security Considerations...... 239 3.4 Unicode in Flask...... 242 3.5 Flask Extension Development...... 244 3.6 Pocoo Styleguide...... 249 3.7 Upgrading to Newer Releases...... 252 3.8 Changelog...... 259 3.9 License...... 275 3.10 How to contribute to Flask...... 276
i Python Module Index 279
Index 281
ii Flask Documentation (1.1.x), Release 1.1.4
Welcome to Flask’s documentation. Get started with Installation and then get an overview with the Quickstart. There is also a more detailed Tutorial that shows how to create a small but complete application with Flask. Common patterns are described in the Patterns for Flask section. The rest of the docs describe each component of Flask in detail, with a full reference in the API section. Flask depends on the Jinja template engine and the Werkzeug WSGI toolkit. The documentation for these libraries can be found at: • Jinja documentation • Werkzeug documentation
CONTENTS 1 Flask Documentation (1.1.x), Release 1.1.4
2 CONTENTS CHAPTER ONE
USER’S GUIDE
This part of the documentation, which is mostly prose, begins with some background information about Flask, then focuses on step-by-step instructions for web development with Flask.
1.1 Foreword
Read this before you get started with Flask. This hopefully answers some questions about the purpose and goals of the project, and when you should or should not be using it.
1.1.1 What does “micro” mean?
“Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but extensible. Flask won’t make many decisions for you, such as what database to use. Those decisions that it does make, such as what templating engine to use, are easy to change. Everything else is up to you, so that Flask can be everything you need and nothing you don’t. By default, Flask does not include a database abstraction layer, form validation or anything else where different libraries already exist that can handle that. Instead, Flask supports extensions to add such functionality to your appli- cation as if it was implemented in Flask itself. Numerous extensions provide database integration, form validation, upload handling, various open authentication technologies, and more. Flask may be “micro”, but it’s ready for pro- duction use on a variety of needs.
1.1.2 Configuration and Conventions
Flask has many configuration values, with sensible defaults, and a few conventions when getting started. By conven- tion, templates and static files are stored in subdirectories within the application’s Python source tree, with the names templates and static respectively. While this can be changed, you usually don’t have to, especially when getting started.
1.1.3 Growing with Flask
Once you have Flask up and running, you’ll find a variety of extensions available in the community to integrate your project for production. The Flask core team reviews extensions and ensures approved extensions do not break with future releases. As your codebase grows, you are free to make the design decisions appropriate for your project. Flask will continue to provide a very simple glue layer to the best that Python has to offer. You can implement advanced patterns in
3 Flask Documentation (1.1.x), Release 1.1.4
SQLAlchemy or another database tool, introduce non-relational data persistence as appropriate, and take advantage of framework-agnostic tools built for WSGI, the Python web interface. Flask includes many hooks to customize its behavior. Should you need more customization, the Flask class is built for subclassing. If you are interested in that, check out the Becoming Big chapter. If you are curious about the Flask design principles, head over to the section about Design Decisions in Flask. Continue to Installation, the Quickstart, or the Foreword for Experienced Programmers.
1.2 Foreword for Experienced Programmers
1.2.1 Thread-Locals in Flask
One of the design decisions in Flask was that simple tasks should be simple; they should not take a lot of code and yet they should not limit you. Because of that, Flask has a few design choices that some people might find surprising or unorthodox. For example, Flask uses thread-local objects internally so that you don’t have to pass objects around from function to function within a request in order to stay threadsafe. This approach is convenient, but requires a valid request context for dependency injection or when attempting to reuse code which uses a value pegged to the request. The Flask project is honest about thread-locals, does not hide them, and calls out in the code and documentation where they are used.
1.2.2 Develop for the Web with Caution
Always keep security in mind when building web applications. If you write a web application, you are probably allowing users to register and leave their data on your server. The users are entrusting you with data. And even if you are the only user that might leave data in your application, you still want that data to be stored securely. Unfortunately, there are many ways the security of a web application can be compromised. Flask protects you against one of the most common security problems of modern web applications: cross-site scripting (XSS). Unless you delib- erately mark insecure HTML as secure, Flask and the underlying Jinja2 template engine have you covered. But there are many more ways to cause security problems. The documentation will warn you about aspects of web development that require attention to security. Some of these security concerns are far more complex than one might think, and we all sometimes underestimate the likelihood that a vulnerability will be exploited - until a clever attacker figures out a way to exploit our applications. And don’t think that your application is not important enough to attract an attacker. Depending on the kind of attack, chances are that automated bots are probing for ways to fill your database with spam, links to malicious software, and the like. Flask is no different from any other framework in that you the developer must build with caution, watching for exploits when building to your requirements.
1.3 Installation
1.3.1 Python Version
We recommend using the latest version of Python 3. Flask supports Python 3.5 and newer, Python 2.7, and PyPy.
4 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.3.2 Dependencies
These distributions will be installed automatically when installing Flask. • Werkzeug implements WSGI, the standard Python interface between applications and servers. • Jinja is a template language that renders the pages your application serves. • MarkupSafe comes with Jinja. It escapes untrusted input when rendering templates to avoid injection attacks. • ItsDangerous securely signs data to ensure its integrity. This is used to protect Flask’s session cookie. • Click is a framework for writing command line applications. It provides the flask command and allows adding custom management commands.
Optional dependencies
These distributions will not be installed automatically. Flask will detect and use them if you install them. • Blinker provides support for Signals. • SimpleJSON is a fast JSON implementation that is compatible with Python’s json module. It is preferred for JSON operations if it is installed. • python-dotenv enables support for Environment Variables From dotenv when running flask commands. • Watchdog provides a faster, more efficient reloader for the development server.
1.3.3 Virtual environments
Use a virtual environment to manage the dependencies for your project, both in development and in production. What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project. Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages. Python 3 comes bundled with the venv module to create virtual environments. If you’re using a modern version of Python, you can continue on to the next section. If you’re using Python 2, see Install virtualenv first.
Create an environment
Create a project folder and a venv folder within:
$ mkdir myproject $ cd myproject $ python3 -m venv venv
On Windows:
$ py -3 -m venv venv
If you needed to install virtualenv because you are using Python 2, use the following command instead:
1.3. Installation 5 Flask Documentation (1.1.x), Release 1.1.4
$ python2 -m virtualenv venv
On Windows:
> \Python27\Scripts\virtualenv.exe venv
Activate the environment
Before you work on your project, activate the corresponding environment:
$ . venv/bin/activate
On Windows:
> venv\Scripts\activate
Your shell prompt will change to show the name of the activated environment.
1.3.4 Install Flask
Within the activated environment, use the following command to install Flask:
$ pip install Flask
Flask is now installed. Check out the Quickstart or go to the Documentation Overview.
Living on the edge
If you want to work with the latest Flask code before it’s released, install or update the code from the master branch:
$ pip install -U https://github.com/pallets/flask/archive/master.tar.gz
1.3.5 Install virtualenv
If you are using Python 2, the venv module is not available. Instead, install virtualenv. On Linux, virtualenv is provided by your package manager:
# Debian, Ubuntu $ sudo apt-get install python-virtualenv
# CentOS, Fedora $ sudo yum install python-virtualenv
# Arch $ sudo pacman -S python-virtualenv
If you are on Mac OS X or Windows, download get-pip.py, then:
$ sudo python2 Downloads/get-pip.py $ sudo python2 -m pip install virtualenv
On Windows, as an administrator:
6 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
> \Python27\python.exe Downloads\get-pip.py > \Python27\python.exe -m pip install virtualenv
Now you can return above and Create an environment.
1.4 Quickstart
Eager to get started? This page gives a good introduction to Flask. It assumes you already have Flask installed. If you do not, head over to the Installation section.
1.4.1 A Minimal Application
A minimal Flask application looks something like this:
from flask import Flask app= Flask(__name__)
@app.route('/') def hello_world(): return 'Hello, World!'
So what did that code do? 1. First we imported the Flask class. An instance of this class will be our WSGI application. 2. Next we create an instance of this class. The first argument is the name of the application’s module or package. If you are using a single module (as in this example), you should use __name__ because depending on if it’s started as application or imported as module the name will be different ('__main__' versus the actual import name). This is needed so that Flask knows where to look for templates, static files, and so on. For more information have a look at the Flask documentation. 3. We then use the route() decorator to tell Flask what URL should trigger our function. 4. The function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user’s browser. Just save it as hello.py or something similar. Make sure to not call your application flask.py because this would conflict with Flask itself. To run the application you can either use the flask command or python’s -m switch with Flask. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP environment variable:
$ export FLASK_APP=hello.py $ flask run * Running on http://127.0.0.1:5000/
If you are on Windows, the environment variable syntax depends on command line interpreter. On Command Prompt:
C:\path\to\app>set FLASK_APP=hello.py
And on PowerShell:
PS C:\path\to\app> $env:FLASK_APP = "hello.py"
Alternatively you can use python -m flask:
1.4. Quickstart 7 Flask Documentation (1.1.x), Release 1.1.4
$ export FLASK_APP=hello.py $ python -m flask run * Running on http://127.0.0.1:5000/
This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see Deployment Options. Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting.
Externally Visible Server If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line:
$ flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.
1.4.2 What to do if the Server does not Start
In case the python -m flask fails or flask does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message.
Old Version of Flask
Versions of Flask older than 0.11 used to have different ways to start the application. In short, the flask command did not exist, and neither did python -m flask. In that case you have two options: either upgrade to newer Flask versions or have a look at the Development Server docs to see the alternative method for running a server.
Invalid Import Name
The FLASK_APP environment variable is the name of the module to import at flask run. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application). It will tell you what it tried to import and why it failed. The most common reason is a typo or because you did not actually create an app object.
1.4.3 Debug Mode
(Want to just log errors and stack traces? See Application Errors) The flask script is nice to start a local development server, but you would have to restart it manually after each change to your code. That is not very nice and Flask can do better. If you enable debug support the server will reload itself on code changes, and it will also provide you with a helpful debugger if things go wrong. To enable all development features (including debug mode) you can export the FLASK_ENV environment variable and set it to development before running the server:
8 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
$ export FLASK_ENV=development $ flask run
(On Windows you need to use set instead of export.) This does the following things: 1. it activates the debugger 2. it activates the automatic reloader 3. it enables the debug mode on the Flask application. You can also control debug mode separately from the environment by exporting FLASK_DEBUG=1. There are more parameters that are explained in the Development Server docs.
Attention Even though the interactive debugger does not work in forking environments (which makes it nearly impossible to use on production servers), it still allows the execution of arbitrary code. This makes it a major security risk and therefore it must never be used on production machines.
Screenshot of the debugger in action:
1.4. Quickstart 9 Flask Documentation (1.1.x), Release 1.1.4
More information on using the debugger can be found in the Werkzeug documentation. Have another debugger in mind? See Working with Debuggers.
1.4.4 Routing
Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page. Use the route() decorator to bind a function to a URL.
@app.route('/') def index(): return 'Index Page'
@app.route('/hello') (continues on next page)
10 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def hello(): return 'Hello, World'
You can do more! You can make parts of the URL dynamic and attach multiple rules to a function.
Variable Rules
You can add variable sections to a URL by marking sections with
from markupsafe import escape
@app.route('/user/
@app.route('/post/
@app.route('/path/
Converter types:
string (default) accepts any text without a slash int accepts positive integers float accepts positive floating point values path like string but also accepts slashes uuid accepts UUID strings
Unique URLs / Redirection Behavior
The following two rules differ in their use of a trailing slash.
@app.route('/projects/') def projects(): return 'The project page'
@app.route('/about') def about(): return 'The about page'
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash, Flask redirects you to the canonical URL with the trailing slash. The canonical URL for the about endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash produces a 404 “Not Found” error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice.
1.4. Quickstart 11 Flask Documentation (1.1.x), Release 1.1.4
URL Building
To build a URL to a specific function, use the url_for() function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters. Why would you want to build URLs using the URL reversing function url_for() instead of hard-coding them into your templates? 1. Reversing is often more descriptive than hard-coding the URLs. 2. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs. 3. URL building handles escaping of special characters and Unicode data transparently. 4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers. 5. If your application is placed outside the URL root, for example, in /myapplication instead of /, url_for() properly handles that for you. For example, here we use the test_request_context() method to try out url_for(). test_request_context() tells Flask to behave as though it’s handling a request even while we use a Python shell. See Context Locals.
from flask import Flask, url_for from markupsafe import escape
app= Flask(__name__)
@app.route('/') def index(): return 'index'
@app.route('/login') def login(): return 'login'
@app.route('/user/
/ /login /login?next=/ /user/John%20Doe
HTTP Methods
Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods.
12 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
from flask import request
@app.route('/login', methods=['GET','POST']) def login(): if request.method =='POST': return do_the_login() else: return show_the_login_form()
If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC. Likewise, OPTIONS is automatically implemented for you.
1.4.5 Static Files
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application. To generate URLs for static files, use the special 'static' endpoint name:
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css.
1.4.6 Rendering Templates
Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the Jinja2 template engine for you automatically. To render a template you can use the render_template() method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template:
from flask import render_template
@app.route('/hello/') @app.route('/hello/
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: Case 1: a module:
/application.py /templates /hello.html
Case 2: a package:
1.4. Quickstart 13 Flask Documentation (1.1.x), Release 1.1.4
/application /__init__.py /templates /hello.html
For templates you can use the full power of Jinja2 templates. Head over to the official Jinja2 Template Documentation for more information. Here is an example template:
Hello {{ name }}!
{% else %}Hello, World!
{% endif %}Inside templates you also have access to the request, session and g1 objects as well as the get_flashed_messages() function. Templates are especially useful if inheritance is used. If you want to know how that works, head over to the Template Inheritance pattern documentation. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer). Automatic escaping is enabled, so if name contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the Markup class or by using the |safe filter in the template. Head over to the Jinja 2 documentation for more examples. Here is a basic introduction to how the Markup class works:
>>> from markupsafe import Markup >>> Markup('Hello %s!')%'' Markup(u'Hello <blink>hacker</blink>!') >>> Markup.escape('') Markup(u'<blink>hacker</blink>') >>> Markup('Marked up » HTML').striptags() u'Marked up \xbb HTML'
Changed in version 0.5: Autoescaping is no longer enabled for all templates. The following extensions for tem- plates trigger autoescaping: .html, .htm, .xml, .xhtml. Templates loaded from a string will have autoescaping disabled.
1.4.7 Accessing Request Data
For web applications it’s crucial to react to the data a client sends to the server. In Flask this information is provided by the global request object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals:
Context Locals
Insider Information 1 Unsure what that g object is? It’s something in which you can store information for your own needs, check the documentation of that object (g) and the Using SQLite 3 with Flask for more information.
14 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
If you want to understand how that works and how you can implement tests with context locals, read this section, otherwise just skip it.
Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand. Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking. So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use the test_request_context() context manager. In combination with the with statement it will bind a test request so that you can interact with it. Here is an example: from flask import request with app.test_request_context('/hello', method='POST'): # now you can do something with the request until the # end of the with block, such as basic assertions: assert request.path =='/hello' assert request.method =='POST'
The other possibility is passing a whole WSGI environment to the request_context() method: from flask import request with app.request_context(environ): assert request.method =='POST'
The Request Object
The request object is documented in the API section and we will not cover it here in detail (see Request). Here is a broad overview of some of the most common operations. First of all you have to import it from the flask module: from flask import request
The current request method is available by using the method attribute. To access form data (data transmitted in a POST or PUT request) you can use the form attribute. Here is a full example of the two attributes mentioned above:
@app.route('/login', methods=['POST','GET']) def login(): error= None if request.method =='POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error='Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error)
1.4. Quickstart 15 Flask Documentation (1.1.x), Release 1.1.4
What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem. To access parameters submitted in the URL (?key=value) you can use the args attribute:
searchword= request.args.get('key','')
We recommend accessing URL parameters with get or by catching the KeyError because users might change the URL and presenting them a 400 bad request page in that case is not user friendly. For a full list of methods and attributes of the request object, head over to the Request documentation.
File Uploads
You can handle uploaded files with Flask easily. Just make sure not to forget to set the enctype="multipart/ form-data" attribute on your HTML form, otherwise the browser will not transmit your files at all. Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the files attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works:
from flask import request
@app.route('/upload', methods=['GET','POST']) def upload_file(): if request.method =='POST': f= request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') ...
If you want to know how the file was named on the client before it was uploaded to your application, you can access the filename attribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through the secure_filename() function that Werkzeug provides for you:
from flask import request from werkzeug.utils import secure_filename
@app.route('/upload', methods=['GET','POST']) def upload_file(): if request.method =='POST': f= request.files['the_file'] f.save('/var/www/uploads/'+ secure_filename(f.filename)) ...
For some better examples, checkout the Uploading Files pattern.
Cookies
To access cookies you can use the cookies attribute. To set cookies you can use the set_cookie method of response objects. The cookies attribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use the Sessions in Flask that add some security on top of cookies for you. Reading cookies:
16 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
from flask import request
@app.route('/') def index(): username= request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing.
Storing cookies:
from flask import make_response
@app.route('/') def index(): resp= make_response(render_template(...)) resp.set_cookie('username','the username') return resp
Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the make_response() function and then modify it. Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the Deferred Request Callbacks pattern. For this also see About Responses.
1.4.8 Redirects and Errors
To redirect a user to another endpoint, use the redirect() function; to abort a request early with an error code, use the abort() function:
from flask import abort, redirect, url_for
@app.route('/') def index(): return redirect(url_for('login'))
@app.route('/login') def login(): abort(401) this_is_never_executed()
This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works. By default a black and white error page is shown for each error code. If you want to customize the error page, you can use the errorhandler() decorator:
from flask import render_template
@app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404
Note the 404 after the render_template() call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well.
1.4. Quickstart 17 Flask Documentation (1.1.x), Release 1.1.4
See Error handlers for more details.
1.4.9 About Responses
The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a 200 OK status code and a text/html mimetype. If the return value is a dict, jsonify() is called to produce a response. The logic that Flask applies to converting return values into response objects is as follows: 1. If a response object of the correct type is returned it’s directly returned from the view. 2. If it’s a string, a response object is created with that data and the default parameters. 3. If it’s a dict, a response object is created using jsonify. 4. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status), (response, headers), or (response, status, headers). The status value will override the status code and headers can be a list or dictionary of additional header values. 5. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object. If you want to get hold of the resulting response object inside the view you can use the make_response() function. Imagine you have a view like this:
@app.errorhandler(404) def not_found(error): return render_template('error.html'), 404
You just need to wrap the return expression with make_response() and get the response object to modify it, then return it:
@app.errorhandler(404) def not_found(error): resp= make_response(render_template('error.html'), 404) resp.headers['X-Something']='A value' return resp
APIs with JSON
A common response format when writing an API is JSON. It’s easy to get started writing such an API with Flask. If you return a dict from a view, it will be converted to a JSON response.
@app.route("/me") def me_api(): user= get_current_user() return { "username": user.username, "theme": user.theme, "image": url_for("user_image", filename=user.image), }
Depending on your API design, you may want to create JSON responses for types other than dict. In that case, use the jsonify() function, which will serialize any supported JSON data type. Or look into Flask community extensions that support more complex applications.
18 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
@app.route("/users") def users_api(): users= get_all_users() return jsonify([user.to_json() for user in users])
1.4.10 Sessions
In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing. In order to use sessions you have to set a secret key. Here is how sessions work: from flask import Flask, session, redirect, url_for, request from markupsafe import escape app= Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret! app.secret_key=b'_5#y2L"F4Q8z \n\xec]/'
@app.route('/') def index(): if 'username' in session: return 'Logged in as %s'% escape(session['username']) return 'You are not logged in'
@app.route('/login', methods=['GET','POST']) def login(): if request.method =='POST': session['username']= request.form['username'] return redirect(url_for('index')) return '''
'''@app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index'))
The escape() mentioned here does escaping for you if you are not using the template engine (as in this example).
How to generate good secret keys A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for Flask.secret_key (or SECRET_KEY):
$ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/'
1.4. Quickstart 19 Flask Documentation (1.1.x), Release 1.1.4
A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers. Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this.
1.4.11 Message Flashing
Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message. To flash a message use the flash() method, to get hold of the messages you can use get_flashed_messages() which is also available in the templates. Check out the Message Flashing for a full example.
1.4.12 Logging
New in version 0.3. Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it’s okay to reply with 400 Bad Request in that situation, but sometimes that won’t do and the code has to continue working. You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use. Here are some example log calls:
app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred')
The attached logger is a standard logging Logger, so head over to the official logging docs for more information. Read more on Application Errors.
1.4.13 Hooking in WSGI Middleware
To add WSGI middleware to your Flask application, wrap the application’s wsgi_app attribute. For example, to apply Werkzeug’s ProxyFix middleware for running behind Nginx:
from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app= ProxyFix(app.wsgi_app)
Wrapping app.wsgi_app instead of app means that app still points at your Flask application, not at the middle- ware, so you can continue to use and configure app directly.
20 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.4.14 Using Flask Extensions
Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask. For more on Flask extensions, have a look at Extensions.
1.4.15 Deploying to a Web Server
Ready to deploy your new Flask app? Go to Deployment Options.
1.5 Tutorial
1.5.1 Project Layout
Create a project directory and enter it:
$ mkdir flask-tutorial $ cd flask-tutorial
Then follow the installation instructions to set up a Python virtual environment and install Flask for your project. The tutorial will assume you’re working from the flask-tutorial directory from now on. The file names at the top of each code block are relative to this directory.
A Flask application can be as simple as a single file.
Listing 1: hello.py from flask import Flask
app= Flask(__name__)
@app.route('/') def hello(): return 'Hello, World!'
However, as a project gets bigger, it becomes overwhelming to keep all the code in one file. Python projects use packages to organize code into multiple modules that can be imported where needed, and the tutorial will do this as well. The project directory will contain: • flaskr/, a Python package containing your application code and files. • tests/, a directory containing test modules. • venv/, a Python virtual environment where Flask and other dependencies are installed. • Installation files telling Python how to install your project. • Version control config, such as git. You should make a habit of using some type of version control for all your projects, no matter the size. • Any other project files you might add in the future.
1.5. Tutorial 21 Flask Documentation (1.1.x), Release 1.1.4
By the end, your project layout will look like this:
/home/user/Projects/flask-tutorial flaskr/ __init__.py db.py schema.sql auth.py blog.py templates/ base.html auth/ login.html register.html blog/ create.html index.html update.html static/ style.css tests/ conftest.py data.sql test_factory.py test_db.py test_auth.py test_blog.py venv/ setup.py MANIFEST.in
If you’re using version control, the following files that are generated while running your project should be ignored. There may be other files based on the editor you use. In general, ignore files that you didn’t write. For example, with git:
22 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Listing 2: .gitignore venv/
*.pyc __pycache__/
instance/
.pytest_cache/ .coverage htmlcov/
dist/ build/ *.egg-info/
Continue to Application Setup.
1.5.2 Application Setup
A Flask application is an instance of the Flask class. Everything about the application, such as configuration and URLs, will be registered with this class. The most straightforward way to create a Flask application is to create a global Flask instance directly at the top of your code, like how the “Hello, World!” example did on the previous page. While this is simple and useful in some cases, it can cause some tricky issues as the project grows. Instead of creating a Flask instance globally, you will create it inside a function. This function is known as the application factory. Any configuration, registration, and other setup the application needs will happen inside the function, then the application will be returned.
The Application Factory
It’s time to start coding! Create the flaskr directory and add the __init__.py file. The __init__.py serves double duty: it will contain the application factory, and it tells Python that the flaskr directory should be treated as a package.
$ mkdir flaskr
Listing 3: flaskr/__init__.py import os
from flask import Flask
def create_app(test_config=None): # create and configure the app app= Flask(__name__, instance_relative_config= True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path,'flaskr.sqlite'), ) (continues on next page)
1.5. Tutorial 23 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page)
if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config)
# ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass
# a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!'
return app create_app is the application factory function. You’ll add to it later in the tutorial, but it already does a lot. 1. app = Flask(__name__, instance_relative_config=True) creates the Flask instance. • __name__ is the name of the current Python module. The app needs to know where it’s located to set up some paths, and __name__ is a convenient way to tell it that. • instance_relative_config=True tells the app that configuration files are relative to the instance folder. The instance folder is located outside the flaskr package and can hold local data that shouldn’t be committed to version control, such as configuration secrets and the database file. 2. app.config.from_mapping() sets some default configuration that the app will use: • SECRET_KEY is used by Flask and extensions to keep data safe. It’s set to 'dev' to provide a convenient value during development, but it should be overridden with a random value when deploying. • DATABASE is the path where the SQLite database file will be saved. It’s under app.instance_path, which is the path that Flask has chosen for the instance folder. You’ll learn more about the database in the next section. 3. app.config.from_pyfile() overrides the default configuration with values taken from the config.py file in the instance folder if it exists. For example, when deploying, this can be used to set a real SECRET_KEY. • test_config can also be passed to the factory, and will be used instead of the instance configuration. This is so the tests you’ll write later in the tutorial can be configured independently of any development values you have configured. 4. os.makedirs() ensures that app.instance_path exists. Flask doesn’t create the instance folder auto- matically, but it needs to be created because your project will create the SQLite database file there. 5. @app.route() creates a simple route so you can see the application working before getting into the rest of the tutorial. It creates a connection between the URL /hello and a function that returns a response, the string 'Hello, World!' in this case.
Run The Application
Now you can run your application using the flask command. From the terminal, tell Flask where to find your application, then run it in development mode. Remember, you should still be in the top-level flask-tutorial
24 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4 directory, not the flaskr package. Development mode shows an interactive debugger whenever a page raises an exception, and restarts the server when- ever you make changes to the code. You can leave it running and just reload the browser page as you follow the tutorial. For Linux and Mac:
$ export FLASK_APP=flaskr $ export FLASK_ENV=development $ flask run
For Windows cmd, use set instead of export:
> set FLASK_APP=flaskr > set FLASK_ENV=development > flask run
For Windows PowerShell, use $env: instead of export:
> $env:FLASK_APP = "flaskr" > $env:FLASK_ENV = "development" > flask run
You’ll see output similar to this:
* Serving Flask app "flaskr" * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 855-212-761
Visit http://127.0.0.1:5000/hello in a browser and you should see the “Hello, World!” message. Congratulations, you’re now running your Flask web application! Continue to Define and Access the Database.
1.5.3 Define and Access the Database
The application will use a SQLite database to store users and posts. Python comes with built-in support for SQLite in the sqlite3 module. SQLite is convenient because it doesn’t require setting up a separate database server and is built-in to Python. How- ever, if concurrent requests try to write to the database at the same time, they will slow down as each write happens sequentially. Small applications won’t notice this. Once you become big, you may want to switch to a different database. The tutorial doesn’t go into detail about SQL. If you are not familiar with it, the SQLite docs describe the language.
Connect to the Database
The first thing to do when working with a SQLite database (and most other Python database libraries) is to create a connection to it. Any queries and operations are performed using the connection, which is closed after the work is finished.
1.5. Tutorial 25 Flask Documentation (1.1.x), Release 1.1.4
In web applications this connection is typically tied to the request. It is created at some point when handling a request, and closed before the response is sent.
Listing 4: flaskr/db.py import sqlite3 import click from flask import current_app, g from flask.cli import with_appcontext def get_db(): if 'db' not in g: g.db= sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory= sqlite3.Row
return g.db def close_db(e=None): db=g.pop('db', None)
if db is not None: db.close() g is a special object that is unique for each request. It is used to store data that might be accessed by multiple functions during the request. The connection is stored and reused instead of creating a new connection if get_db is called a second time in the same request. current_app is another special object that points to the Flask application handling the request. Since you used an application factory, there is no application object when writing the rest of your code. get_db will be called when the application has been created and is handling a request, so current_app can be used. sqlite3.connect() establishes a connection to the file pointed at by the DATABASE configuration key. This file doesn’t have to exist yet, and won’t until you initialize the database later. sqlite3.Row tells the connection to return rows that behave like dicts. This allows accessing the columns by name. close_db checks if a connection was created by checking if g.db was set. If the connection exists, it is closed. Further down you will tell your application about the close_db function in the application factory so that it is called after each request.
Create the Tables
In SQLite, data is stored in tables and columns. These need to be created before you can store and retrieve data. Flaskr will store users in the user table, and posts in the post table. Create a file with the SQL commands needed to create empty tables:
Listing 5: flaskr/schema.sql DROP TABLEIF EXISTS user ; DROP TABLEIF EXISTS post;
(continues on next page)
26 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) CREATE TABLE user ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL );
CREATE TABLE post ( id INTEGER PRIMARY KEY AUTOINCREMENT, author_id INTEGER NOT NULL, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, title TEXT NOT NULL, body TEXT NOT NULL, FOREIGN KEY (author_id) REFERENCES user (id) );
Add the Python functions that will run these SQL commands to the db.py file:
Listing 6: flaskr/db.py def init_db(): db= get_db()
with current_app.open_resource('schema.sql') as f: db.executescript(f.read().decode('utf8'))
@click.command('init-db') @with_appcontext def init_db_command(): """Clear the existing data and create new tables.""" init_db() click.echo('Initialized the database.')
open_resource() opens a file relative to the flaskr package, which is useful since you won’t necessarily know where that location is when deploying the application later. get_db returns a database connection, which is used to execute the commands read from the file. click.command() defines a command line command called init-db that calls the init_db function and shows a success message to the user. You can read Command Line Interface to learn more about writing commands.
Register with the Application
The close_db and init_db_command functions need to be registered with the application instance; otherwise, they won’t be used by the application. However, since you’re using a factory function, that instance isn’t available when writing the functions. Instead, write a function that takes an application and does the registration.
Listing 7: flaskr/db.py def init_app(app): app.teardown_appcontext(close_db) app.cli.add_command(init_db_command)
app.teardown_appcontext() tells Flask to call that function when cleaning up after returning the response. app.cli.add_command() adds a new command that can be called with the flask command.
1.5. Tutorial 27 Flask Documentation (1.1.x), Release 1.1.4
Import and call this function from the factory. Place the new code at the end of the factory function before returning the app.
Listing 8: flaskr/__init__.py def create_app(): app=... # existing code omitted
from. import db db.init_app(app)
return app
Initialize the Database File
Now that init-db has been registered with the app, it can be called using the flask command, similar to the run command from the previous page.
Note: If you’re still running the server from the previous page, you can either stop the server, or run this command in a new terminal. If you use a new terminal, remember to change to your project directory and activate the env as described in Activate the environment. You’ll also need to set FLASK_APP and FLASK_ENV as shown on the previous page.
Run the init-db command:
$ flask init-db Initialized the database.
There will now be a flaskr.sqlite file in the instance folder in your project. Continue to Blueprints and Views.
1.5.4 Blueprints and Views
A view function is the code you write to respond to requests to your application. Flask uses patterns to match the incoming request URL to the view that should handle it. The view returns data that Flask turns into an outgoing response. Flask can also go the other direction and generate a URL to a view based on its name and arguments.
Create a Blueprint
A Blueprint is a way to organize a group of related views and other code. Rather than registering views and other code directly with an application, they are registered with a blueprint. Then the blueprint is registered with the application when it is available in the factory function. Flaskr will have two blueprints, one for authentication functions and one for the blog posts functions. The code for each blueprint will go in a separate module. Since the blog needs to know about authentication, you’ll write the authentication one first.
28 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Listing 9: flaskr/auth.py import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for ) from werkzeug.security import check_password_hash, generate_password_hash from flaskr.db import get_db bp= Blueprint('auth', __name__, url_prefix='/auth')
This creates a Blueprint named 'auth'. Like the application object, the blueprint needs to know where it’s defined, so __name__ is passed as the second argument. The url_prefix will be prepended to all the URLs associated with the blueprint. Import and register the blueprint from the factory using app.register_blueprint(). Place the new code at the end of the factory function before returning the app.
Listing 10: flaskr/__init__.py def create_app(): app=... # existing code omitted
from. import auth app.register_blueprint(auth.bp)
return app
The authentication blueprint will have views to register new users and to log in and log out.
The First View: Register
When the user visits the /auth/register URL, the register view will return HTML with a form for them to fill out. When they submit the form, it will validate their input and either show the form again with an error message or create the new user and go to the login page. For now you will just write the view code. On the next page, you’ll write templates to generate the HTML form.
Listing 11: flaskr/auth.py @bp.route('/register', methods=('GET','POST')) def register(): if request.method =='POST': username= request.form['username'] password= request.form['password'] db= get_db() error= None
if not username: error='Username is required.' elif not password: error='Password is required.' elif db.execute( 'SELECT id FROM user WHERE username = ?', (username,) (continues on next page)
1.5. Tutorial 29 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) ).fetchone() is not None: error='User {} is already registered.'.format(username)
if error is None: db.execute( 'INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password)) ) db.commit() return redirect(url_for('auth.login'))
flash(error)
return render_template('auth/register.html')
Here’s what the register view function is doing: 1. @bp.route associates the URL /register with the register view function. When Flask receives a request to /auth/register, it will call the register view and use the return value as the response. 2. If the user submitted the form, request.method will be 'POST'. In this case, start validating the input. 3. request.form is a special type of dict mapping submitted form keys and values. The user will input their username and password. 4. Validate that username and password are not empty. 5. Validate that username is not already registered by querying the database and checking if a result is returned. db.execute takes a SQL query with ? placeholders for any user input, and a tuple of values to replace the placeholders with. The database library will take care of escaping the values so you are not vulnerable to a SQL injection attack. fetchone() returns one row from the query. If the query returned no results, it returns None. Later, fetchall() is used, which returns a list of all results. 6. If validation succeeds, insert the new user data into the database. For security, passwords should never be stored in the database directly. Instead, generate_password_hash() is used to securely hash the password, and that hash is stored. Since this query modifies data, db.commit() needs to be called afterwards to save the changes. 7. After storing the user, they are redirected to the login page. url_for() generates the URL for the login view based on its name. This is preferable to writing the URL directly as it allows you to change the URL later without changing all code that links to it. redirect() generates a redirect response to the generated URL. 8. If validation fails, the error is shown to the user. flash() stores messages that can be retrieved when rendering the template. 9. When the user initially navigates to auth/register, or there was a validation error, an HTML page with the registration form should be shown. render_template() will render a template containing the HTML, which you’ll write in the next step of the tutorial.
Login
This view follows the same pattern as the register view above.
30 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Listing 12: flaskr/auth.py @bp.route('/login', methods=('GET','POST')) def login(): if request.method =='POST': username= request.form['username'] password= request.form['password'] db= get_db() error= None user= db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone()
if user is None: error='Incorrect username.' elif not check_password_hash(user['password'], password): error='Incorrect password.'
if error is None: session.clear() session['user_id']= user['id'] return redirect(url_for('index'))
flash(error)
return render_template('auth/login.html')
There are a few differences from the register view: 1. The user is queried first and stored in a variable for later use. 2. check_password_hash() hashes the submitted password in the same way as the stored hash and securely compares them. If they match, the password is valid. 3. session is a dict that stores data across requests. When validation succeeds, the user’s id is stored in a new session. The data is stored in a cookie that is sent to the browser, and the browser then sends it back with subsequent requests. Flask securely signs the data so that it can’t be tampered with. Now that the user’s id is stored in the session, it will be available on subsequent requests. At the beginning of each request, if a user is logged in their information should be loaded and made available to other views.
Listing 13: flaskr/auth.py @bp.before_app_request def load_logged_in_user(): user_id= session.get('user_id')
if user_id is None: g.user= None else: g.user= get_db().execute( 'SELECT * FROM user WHERE id = ?', (user_id,) ).fetchone()
bp.before_app_request() registers a function that runs before the view function, no matter what URL is requested. load_logged_in_user checks if a user id is stored in the session and gets that user’s data from the database, storing it on g.user, which lasts for the length of the request. If there is no user id, or if the id doesn’t exist, g.user will be None.
1.5. Tutorial 31 Flask Documentation (1.1.x), Release 1.1.4
Logout
To log out, you need to remove the user id from the session. Then load_logged_in_user won’t load a user on subsequent requests.
Listing 14: flaskr/auth.py @bp.route('/logout') def logout(): session.clear() return redirect(url_for('index'))
Require Authentication in Other Views
Creating, editing, and deleting blog posts will require a user to be logged in. A decorator can be used to check this for each view it’s applied to.
Listing 15: flaskr/auth.py def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for('auth.login'))
return view(**kwargs)
return wrapped_view
This decorator returns a new view function that wraps the original view it’s applied to. The new function checks if a user is loaded and redirects to the login page otherwise. If a user is loaded the original view is called and continues normally. You’ll use this decorator when writing the blog views.
Endpoints and URLs
The url_for() function generates the URL to a view based on a name and arguments. The name associated with a view is also called the endpoint, and by default it’s the same as the name of the view function. For example, the hello() view that was added to the app factory earlier in the tutorial has the name 'hello' and can be linked to with url_for('hello'). If it took an argument, which you’ll see later, it would be linked to using url_for('hello', who='World'). When using a blueprint, the name of the blueprint is prepended to the name of the function, so the endpoint for the login function you wrote above is 'auth.login' because you added it to the 'auth' blueprint. Continue to Templates.
1.5.5 Templates
You’ve written the authentication views for your application, but if you’re running the server and try to go to any of the URLs, you’ll see a TemplateNotFound error. That’s because the views are calling render_template(), but you haven’t written the templates yet. The template files will be stored in the templates directory inside the flaskr package.
32 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Templates are files that contain static data as well as placeholders for dynamic data. A template is rendered with specific data to produce a final document. Flask uses the Jinja template library to render templates. In your application, you will use templates to render HTML which will display in the user’s browser. In Flask, Jinja is configured to autoescape any data that is rendered in HTML templates. This means that it’s safe to render user input; any characters they’ve entered that could mess with the HTML, such as < and > will be escaped with safe values that look the same in the browser but don’t cause unwanted effects. Jinja looks and behaves mostly like Python. Special delimiters are used to distinguish Jinja syntax from the static data in the template. Anything between {{ and }} is an expression that will be output to the final document. {% and %} denotes a control flow statement like if and for. Unlike Python, blocks are denoted by start and end tags rather than indentation since static text within a block could change indentation.
The Base Layout
Each page in the application will have the same basic layout around a different body. Instead of writing the entire HTML structure in each template, each template will extend a base template and override specific sections.
Listing 16: flaskr/templates/base.html
g is automatically available in templates. Based on if g.user is set (from load_logged_in_user), either the username and a log out link are displayed, or links to register and log in are displayed. url_for() is also automatically available, and is used to generate URLs to views instead of writing them out manually. After the page title, and before the content, the template loops over each message returned by get_flashed_messages(). You used flash() in the views to show error messages, and this is the code that will display them. There are three blocks defined here that will be overridden in the other templates: 1. {% block title %} will change the title displayed in the browser’s tab and window title. 2. {% block header %} is similar to title but will change the title displayed on the page.
1.5. Tutorial 33 Flask Documentation (1.1.x), Release 1.1.4
3. {% block content %} is where the content of each page goes, such as the login form or a blog post. The base template is directly in the templates directory. To keep the others organized, the templates for a blueprint will be placed in a directory with the same name as the blueprint.
Register
Listing 17: flaskr/templates/auth/register.html {% extends 'base.html' %}
{% block header %}
{% block title %}Register{% endblock %}
{% endblock %}{% block content %}
{% endblock %}{% extends 'base.html' %} tells Jinja that this template should replace the blocks from the base template. All the rendered content must appear inside {% block %} tags that override blocks from the base template. A useful pattern used here is to place {% block title %} inside {% block header %}. This will set the title block and then output the value of it into the header block, so that both the window and page share the same title without writing it twice. The input tags are using the required attribute here. This tells the browser not to submit the form until those fields are filled in. If the user is using an older browser that doesn’t support that attribute, or if they are using something besides a browser to make requests, you still want to validate the data in the Flask view. It’s important to always fully validate the data on the server, even if the client does some validation as well.
Log In
This is identical to the register template except for the title and submit button.
Listing 18: flaskr/templates/auth/login.html {% extends 'base.html' %}
{% block header %}
{% block title %}Log In{% endblock %}
{% endblock %}{% block content %}
{% endblock %}Register A User
Now that the authentication templates are written, you can register a user. Make sure the server is still running (flask run if it’s not), then go to http://127.0.0.1:5000/auth/register. Try clicking the “Register” button without filling out the form and see that the browser shows an error message. Try removing the required attributes from the register.html template and click “Register” again. Instead of the browser showing an error, the page will reload and the error from flash() in the view will be shown. Fill out a username and password and you’ll be redirected to the login page. Try entering an incorrect username, or the correct username and incorrect password. If you log in you’ll get an error because there’s no index view to redirect to yet. Continue to Static Files.
1.5.6 Static Files
The authentication views and templates work, but they look very plain right now. Some CSS can be added to add style to the HTML layout you constructed. The style won’t change, so it’s a static file rather than a template. Flask automatically adds a static view that takes a path relative to the flaskr/static directory and serves it. The base.html template already has a link to the style.css file:
{{ url_for('static', filename='style.css') }}
Besides CSS, other types of static files might be files with JavaScript functions, or a logo image. They are all placed under the flaskr/static directory and referenced with url_for('static', filename='...'). This tutorial isn’t focused on how to write CSS, so you can just copy the following into the flaskr/static/ style.css file:
Listing 19: flaskr/static/style.css html { font-family: sans-serif; background: #eee; padding:1 rem;} body { max-width: 960px; margin:0 auto; background: white;} h1 { font-family: serif; color: #377ba8; margin:1 rem 0;} a { color: #377ba8;} hr { border: none; border-top:1 px solid lightgray;} nav { background: lightgray; display: flex; align-items: center; padding:0 0.5 rem;} nav h1 { flex: auto; margin:0;} nav h1a { text-decoration: none; padding: 0.25rem 0.5rem;} nav ul { display: flex; list-style: none; margin:0; padding:0;} nav ul lia , nav ul li span, header .action { display: block; padding: 0.5rem;} .content { padding:01 rem 1rem;} .content > header { border-bottom:1 px solid lightgray; display: flex; align-items:
˓→flex-end;} .content > header h1 { flex: auto; margin:1 rem 0 0.25rem 0;} .flash { margin:1 em 0; padding:1 em; background: #cae6f6; border:1 px solid #377ba8;
˓→} .post > header { display: flex; align-items: flex-end; font-size: 0.85em;} .post > header > div:first-of-type { flex: auto;} .post > header h1 { font-size: 1.5em; margin-bottom:0;} (continues on next page)
1.5. Tutorial 35 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) .post .about { color: slategray; font-style: italic;} .post .body { white-space: pre-line;} .content:last-child { margin-bottom:0;} .content form { margin:1 em 0; display: flex; flex-direction: column;} .content label { font-weight: bold; margin-bottom: 0.5em;} .content input,. content textarea { margin-bottom:1 em;} .content textarea { min-height: 12em; resize: vertical;} input.danger { color: #cc2f2e;} input[type=submit]{ align-self: start; min-width: 10em;}
You can find a less compact version of style.css in the example code. Go to http://127.0.0.1:5000/auth/login and the page should look like the screenshot below.
You can read more about CSS from Mozilla’s documentation. If you change a static file, refresh the browser page. If the change doesn’t show up, try clearing your browser’s cache. Continue to Blog Blueprint.
1.5.7 Blog Blueprint
You’ll use the same techniques you learned about when writing the authentication blueprint to write the blog blueprint. The blog should list all posts, allow logged in users to create posts, and allow the author of a post to edit or delete it. As you implement each view, keep the development server running. As you save your changes, try going to the URL in your browser and testing them out.
36 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
The Blueprint
Define the blueprint and register it in the application factory.
Listing 20: flaskr/blog.py from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort
from flaskr.auth import login_required from flaskr.db import get_db
bp= Blueprint('blog', __name__)
Import and register the blueprint from the factory using app.register_blueprint(). Place the new code at the end of the factory function before returning the app.
Listing 21: flaskr/__init__.py def create_app(): app=... # existing code omitted
from. import blog app.register_blueprint(blog.bp) app.add_url_rule('/', endpoint='index')
return app
Unlike the auth blueprint, the blog blueprint does not have a url_prefix. So the index view will be at /, the create view at /create, and so on. The blog is the main feature of Flaskr, so it makes sense that the blog index will be the main index. However, the endpoint for the index view defined below will be blog.index. Some of the authentication views referred to a plain index endpoint. app.add_url_rule() associates the endpoint name 'index' with the / url so that url_for('index') or url_for('blog.index') will both work, generating the same / URL either way. In another application you might give the blog blueprint a url_prefix and define a separate index view in the application factory, similar to the hello view. Then the index and blog.index endpoints and URLs would be different.
Index
The index will show all of the posts, most recent first. A JOIN is used so that the author information from the user table is available in the result.
Listing 22: flaskr/blog.py @bp.route('/') def index(): db= get_db() posts= db.execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' (continues on next page)
1.5. Tutorial 37 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) ' ORDER BY created DESC' ).fetchall() return render_template('blog/index.html', posts=posts)
Listing 23: flaskr/templates/blog/index.html {% extends 'base.html' %}
{% block header %}
{% block title %}Posts{% endblock %}
{% if g.user %} New {% endif %} {% endblock %}{% block content %} {% for post in posts %} ˓→'%Y-%m-%d') }} ˓→a> {% endif %} {{ post['body'] }}{{ post['title'] }}
{% endif %} {% endfor %} {% endblock %}
When a user is logged in, the header block adds a link to the create view. When the user is the author of a post, they’ll see an “Edit” link to the update view for that post. loop.last is a special variable available inside Jinja for loops. It’s used to display a line after each post except the last one, to visually separate them.
Create
The create view works the same as the auth register view. Either the form is displayed, or the posted data is validated and the post is added to the database or an error is shown. The login_required decorator you wrote earlier is used on the blog views. A user must be logged in to visit these views, otherwise they will be redirected to the login page.
Listing 24: flaskr/blog.py @bp.route('/create', methods=('GET','POST')) @login_required def create(): if request.method =='POST': (continues on next page)
38 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) title= request.form['title'] body= request.form['body'] error= None
if not title: error='Title is required.'
if error is not None: flash(error) else: db= get_db() db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', (title, body, g.user['id']) ) db.commit() return redirect(url_for('blog.index'))
return render_template('blog/create.html')
Listing 25: flaskr/templates/blog/create.html {% extends 'base.html' %}
{% block header %}
{% block title %}New Post{% endblock %}
{% endblock %}{% block content %}
{% endblock %}Update
Both the update and delete views will need to fetch a post by id and check if the author matches the logged in user. To avoid duplicating code, you can write a function to get the post and call it from each view.
Listing 26: flaskr/blog.py def get_post(id, check_author=True): post= get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone()
if post is None: (continues on next page)
1.5. Tutorial 39 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) abort(404,"Post id {0} doesn't exist.".format(id))
if check_author and post['author_id'] !=g.user['id']: abort(403)
return post
abort() will raise a special exception that returns an HTTP status code. It takes an optional message to show with the error, otherwise a default message is used. 404 means “Not Found”, and 403 means “Forbidden”. (401 means “Unauthorized”, but you redirect to the login page instead of returning that status.) The check_author argument is defined so that the function can be used to get a post without checking the author. This would be useful if you wrote a view to show an individual post on a page, where the user doesn’t matter because they’re not modifying the post.
Listing 27: flaskr/blog.py @bp.route('/
if request.method =='POST': title= request.form['title'] body= request.form['body'] error= None
if not title: error='Title is required.'
if error is not None: flash(error) else: db= get_db() db.execute( 'UPDATE post SET title = ?, body = ?' ' WHERE id = ?', (title, body, id) ) db.commit() return redirect(url_for('blog.index'))
return render_template('blog/update.html', post=post)
Unlike the views you’ve written so far, the update function takes an argument, id. That corresponds to the
40 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Listing 28: flaskr/templates/blog/update.html {% extends 'base.html' %}
{% block header %}
{% block title %}Edit "{{ post['title'] }}"{% endblock %}
{% endblock %}{% block content %}
{% endblock %}
This template has two forms. The first posts the edited data to the current page (/
Delete
The delete view doesn’t have its own template, the delete button is part of update.html and posts to the /
Listing 29: flaskr/blog.py @bp.route('/
Congratulations, you’ve now finished writing your application! Take some time to try out everything in the browser. However, there’s still more to do before the project is complete. Continue to Make the Project Installable.
1.5. Tutorial 41 Flask Documentation (1.1.x), Release 1.1.4
1.5.8 Make the Project Installable
Making your project installable means that you can build a distribution file and install that in another environment, just like you installed Flask in your project’s environment. This makes deploying your project the same as installing any other library, so you’re using all the standard Python tools to manage everything. Installing also comes with other benefits that might not be obvious from the tutorial or as a new Python user, including: • Currently, Python and Flask understand how to use the flaskr package only because you’re running from your project’s directory. Installing means you can import it no matter where you run from. • You can manage your project’s dependencies just like other packages do, so pip install yourproject. whl installs them. • Test tools can isolate your test environment from your development environment.
Note: This is being introduced late in the tutorial, but in your future projects you should always start with this.
Describe the Project
The setup.py file describes your project and the files that belong to it.
Listing 30: setup.py from setuptools import find_packages, setup
setup( name='flaskr', version='1.0.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'flask', ], )
packages tells Python what package directories (and the Python files they contain) to include. find_packages() finds these directories automatically so you don’t have to type them out. To include other files, such as the static and templates directories, include_package_data is set. Python needs another file named MANIFEST.in to tell what this other data is.
Listing 31: MANIFEST.in include flaskr/schema.sql graft flaskr/static graft flaskr/templates global-exclude *.pyc
This tells Python to copy everything in the static and templates directories, and the schema.sql file, but to exclude all bytecode files. See the official packaging guide for another explanation of the files and options used.
42 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Install the Project
Use pip to install your project in the virtual environment.
$ pip install -e .
This tells pip to find setup.py in the current directory and install it in editable or development mode. Editable mode means that as you make changes to your local code, you’ll only need to re-install if you change the metadata about the project, such as its dependencies. You can observe that the project is now installed with pip list.
$ pip list
Package Version Location ------click 6.7 Flask 1.0 flaskr 1.0.0 /home/user/Projects/flask-tutorial itsdangerous 0.24 Jinja2 2.10 MarkupSafe 1.0 pip 9.0.3 setuptools 39.0.1 Werkzeug 0.14.1 wheel 0.30.0
Nothing changes from how you’ve been running your project so far. FLASK_APP is still set to flaskr and flask run still runs the application, but you can call it from anywhere, not just the flask-tutorial directory. Continue to Test Coverage.
1.5.9 Test Coverage
Writing unit tests for your application lets you check that the code you wrote works the way you expect. Flask provides a test client that simulates requests to the application and returns the response data. You should test as much of your code as possible. Code in functions only runs when the function is called, and code in branches, such as if blocks, only runs when the condition is met. You want to make sure that each function is tested with data that covers each branch. The closer you get to 100% coverage, the more comfortable you can be that making a change won’t unexpectedly change other behavior. However, 100% coverage doesn’t guarantee that your application doesn’t have bugs. In partic- ular, it doesn’t test how the user interacts with the application in the browser. Despite this, test coverage is an important tool to use during development.
Note: This is being introduced late in the tutorial, but in your future projects you should test as you develop.
You’ll use pytest and coverage to test and measure your code. Install them both:
$ pip install pytest coverage
1.5. Tutorial 43 Flask Documentation (1.1.x), Release 1.1.4
Setup and Fixtures
The test code is located in the tests directory. This directory is next to the flaskr package, not inside it. The tests/conftest.py file contains setup functions called fixtures that each test will use. Tests are in Python modules that start with test_, and each test function in those modules also starts with test_. Each test will create a new temporary database file and populate some data that will be used in the tests. Write a SQL file to insert that data.
Listing 32: tests/data.sql INSERT INTO user (username, password) VALUES ('test', 'pbkdf2:sha256:50000$TCI4GzcX
˓→$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'), ('other', 'pbkdf2:sha256:50000$kJPKsz6N
˓→$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');
INSERT INTO post (title, body, author_id, created) VALUES ('test title', 'test'||x'0a'|| 'body',1, '2018-01-01 00:00:00');
The app fixture will call the factory and pass test_config to configure the application and database for testing instead of using your local development configuration.
Listing 33: tests/conftest.py import os import tempfile import pytest from flaskr import create_app from flaskr.db import get_db, init_db with open(os.path.join(os.path.dirname(__file__),'data.sql'),'rb') as f: _data_sql=f.read().decode('utf8')
@pytest.fixture def app(): db_fd, db_path= tempfile.mkstemp()
app= create_app({ 'TESTING': True, 'DATABASE': db_path, })
with app.app_context(): init_db() get_db().executescript(_data_sql)
yield app
os.close(db_fd) os.unlink(db_path)
@pytest.fixture (continues on next page)
44 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def client(app): return app.test_client()
@pytest.fixture def runner(app): return app.test_cli_runner()
tempfile.mkstemp() creates and opens a temporary file, returning the file object and the path to it. The DATABASE path is overridden so it points to this temporary path instead of the instance folder. After setting the path, the database tables are created and the test data is inserted. After the test is over, the temporary file is closed and removed. TESTING tells Flask that the app is in test mode. Flask changes some internal behavior so it’s easier to test, and other extensions can also use the flag to make testing them easier. The client fixture calls app.test_client() with the application object created by the app fixture. Tests will use the client to make requests to the application without running the server. The runner fixture is similar to client. app.test_cli_runner() creates a runner that can call the Click commands registered with the application. Pytest uses fixtures by matching their function names with the names of arguments in the test functions. For example, the test_hello function you’ll write next takes a client argument. Pytest matches that with the client fixture function, calls it, and passes the returned value to the test function.
Factory
There’s not much to test about the factory itself. Most of the code will be executed for each test already, so if something fails the other tests will notice. The only behavior that can change is passing test config. If config is not passed, there should be some default config- uration, otherwise the configuration should be overridden.
Listing 34: tests/test_factory.py from flaskr import create_app
def test_config(): assert not create_app().testing assert create_app({'TESTING': True}).testing
def test_hello(client): response= client.get('/hello') assert response.data ==b'Hello, World!'
You added the hello route as an example when writing the factory at the beginning of the tutorial. It returns “Hello, World!”, so the test checks that the response data matches.
Database
Within an application context, get_db should return the same connection each time it’s called. After the context, the connection should be closed.
1.5. Tutorial 45 Flask Documentation (1.1.x), Release 1.1.4
Listing 35: tests/test_db.py import sqlite3 import pytest from flaskr.db import get_db def test_get_close_db(app): with app.app_context(): db= get_db() assert db is get_db()
with pytest.raises(sqlite3.ProgrammingError) as e: db.execute('SELECT 1')
assert 'closed' in str(e.value)
The init-db command should call the init_db function and output a message.
Listing 36: tests/test_db.py def test_init_db_command(runner, monkeypatch): class Recorder(object): called= False
def fake_init_db(): Recorder.called= True
monkeypatch.setattr('flaskr.db.init_db', fake_init_db) result= runner.invoke(args=['init-db']) assert 'Initialized' in result.output assert Recorder.called
This test uses Pytest’s monkeypatch fixture to replace the init_db function with one that records that it’s been called. The runner fixture you wrote above is used to call the init-db command by name.
Authentication
For most of the views, a user needs to be logged in. The easiest way to do this in tests is to make a POST request to the login view with the client. Rather than writing that out every time, you can write a class with methods to do that, and use a fixture to pass it the client for each test.
Listing 37: tests/conftest.py class AuthActions(object): def __init__(self, client): self._client= client
def login(self, username='test', password='test'): return self._client.post( '/auth/login', data={'username': username,'password': password} )
def logout(self): (continues on next page)
46 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) return self._client.get('/auth/logout')
@pytest.fixture def auth(client): return AuthActions(client)
With the auth fixture, you can call auth.login() in a test to log in as the test user, which was inserted as part of the test data in the app fixture. The register view should render successfully on GET. On POST with valid form data, it should redirect to the login URL and the user’s data should be in the database. Invalid data should display error messages.
Listing 38: tests/test_auth.py import pytest from flask import g, session from flaskr.db import get_db
def test_register(client, app): assert client.get('/auth/register').status_code == 200 response= client.post( '/auth/register', data={'username':'a','password':'a'} ) assert 'http://localhost/auth/login' == response.headers['Location']
with app.app_context(): assert get_db().execute( "select * from user where username ='a'", ).fetchone() is not None
@pytest.mark.parametrize(('username','password','message'), ( ('','',b'Username is required.'), ('a','',b'Password is required.'), ('test','test',b'already registered'), )) def test_register_validate_input(client, username, password, message): response= client.post( '/auth/register', data={'username': username,'password': password} ) assert message in response.data
client.get() makes a GET request and returns the Response object returned by Flask. Similarly, client. post() makes a POST request, converting the data dict into form data. To test that the page renders successfully, a simple request is made and checked for a 200 OK status_code. If rendering failed, Flask would return a 500 Internal Server Error code. headers will have a Location header with the login URL when the register view redirects to the login view. data contains the body of the response as bytes. If you expect a certain value to render on the page, check that it’s in data. Bytes must be compared to bytes. If you want to compare Unicode text, use get_data(as_text=True) instead. pytest.mark.parametrize tells Pytest to run the same test function with different arguments. You use it here
1.5. Tutorial 47 Flask Documentation (1.1.x), Release 1.1.4
to test different invalid input and error messages without writing the same code three times. The tests for the login view are very similar to those for register. Rather than testing the data in the database, session should have user_id set after logging in.
Listing 39: tests/test_auth.py def test_login(client, auth): assert client.get('/auth/login').status_code == 200 response= auth.login() assert response.headers['Location'] =='http://localhost/'
with client: client.get('/') assert session['user_id'] ==1 assert g.user['username'] =='test'
@pytest.mark.parametrize(('username','password','message'), ( ('a','test',b'Incorrect username.'), ('test','a',b'Incorrect password.'), )) def test_login_validate_input(auth, username, password, message): response= auth.login(username, password) assert message in response.data
Using client in a with block allows accessing context variables such as session after the response is returned. Normally, accessing session outside of a request would raise an error. Testing logout is the opposite of login. session should not contain user_id after logging out.
Listing 40: tests/test_auth.py def test_logout(client, auth): auth.login()
with client: auth.logout() assert 'user_id' not in session
Blog
All the blog views use the auth fixture you wrote earlier. Call auth.login() and subsequent requests from the client will be logged in as the test user. The index view should display information about the post that was added with the test data. When logged in as the author, there should be a link to edit the post. You can also test some more authentication behavior while testing the index view. When not logged in, each page shows links to log in or register. When logged in, there’s a link to log out.
Listing 41: tests/test_blog.py import pytest from flaskr.db import get_db
(continues on next page)
48 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def test_index(client, auth): response= client.get('/') assert b"Log In" in response.data assert b"Register" in response.data
auth.login() response= client.get('/') assert b'Log Out' in response.data assert b'test title' in response.data assert b'by test on 2018-01-01' in response.data assert b'test\nbody' in response.data assert b'href="/1/update"' in response.data
A user must be logged in to access the create, update, and delete views. The logged in user must be the author of the post to access update and delete, otherwise a 403 Forbidden status is returned. If a post with the given id doesn’t exist, update and delete should return 404 Not Found.
Listing 42: tests/test_blog.py @pytest.mark.parametrize('path',( '/create', '/1/update', '/1/delete', )) def test_login_required(client, path): response= client.post(path) assert response.headers['Location'] =='http://localhost/auth/login' def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db= get_db() db.execute('UPDATE post SET author_id = 2 WHERE id = 1') db.commit()
auth.login() # current user can't modify other user's post assert client.post('/1/update').status_code == 403 assert client.post('/1/delete').status_code == 403 # current user doesn't see edit link assert b'href="/1/update"' not in client.get('/').data
@pytest.mark.parametrize('path',( '/2/update', '/2/delete', )) def test_exists_required(client, auth, path): auth.login() assert client.post(path).status_code == 404
The create and update views should render and return a 200 OK status for a GET request. When valid data is sent in a POST request, create should insert the new post data into the database, and update should modify the existing data. Both pages should show an error message on invalid data.
1.5. Tutorial 49 Flask Documentation (1.1.x), Release 1.1.4
Listing 43: tests/test_blog.py def test_create(client, auth, app): auth.login() assert client.get('/create').status_code == 200 client.post('/create', data={'title':'created','body':''})
with app.app_context(): db= get_db() count= db.execute('SELECT COUNT(id) FROM post').fetchone()[0] assert count ==2 def test_update(client, auth, app): auth.login() assert client.get('/1/update').status_code == 200 client.post('/1/update', data={'title':'updated','body':''})
with app.app_context(): db= get_db() post= db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post['title'] =='updated'
@pytest.mark.parametrize('path',( '/create', '/1/update', )) def test_create_update_validate(client, auth, path): auth.login() response= client.post(path, data={'title':'','body':''}) assert b'Title is required.' in response.data
The delete view should redirect to the index URL and the post should no longer exist in the database.
Listing 44: tests/test_blog.py def test_delete(client, auth, app): auth.login() response= client.post('/1/delete') assert response.headers['Location'] =='http://localhost/'
with app.app_context(): db= get_db() post= db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post is None
Running the Tests
Some extra configuration, which is not required but makes running tests with coverage less verbose, can be added to the project’s setup.cfg file.
Listing 45: setup.cfg [tool:pytest] testpaths = tests (continues on next page)
50 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page)
[coverage:run] branch = True source = flaskr
To run the tests, use the pytest command. It will find and run all the test functions you’ve written.
$ pytest
======test session starts ======platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0 rootdir: /home/user/Projects/flask-tutorial, inifile: setup.cfg collected 23 items tests/test_auth.py ...... [ 34%] tests/test_blog.py ...... [ 86%] tests/test_db.py .. [ 95%] tests/test_factory.py .. [100%]
======24 passed in 0.64 seconds ======
If any tests fail, pytest will show the error that was raised. You can run pytest -v to get a list of each test function rather than dots. To measure the code coverage of your tests, use the coverage command to run pytest instead of running it directly.
$ coverage run -m pytest
You can either view a simple coverage report in the terminal:
$ coverage report
Name Stmts Miss Branch BrPart Cover ------flaskr/__init__.py 21 0 2 0 100% flaskr/auth.py 54 0 22 0 100% flaskr/blog.py 54 0 16 0 100% flaskr/db.py 24 0 4 0 100% ------TOTAL 153 0 44 0 100%
An HTML report allows you to see which lines were covered in each file:
$ coverage html
This generates files in the htmlcov directory. Open htmlcov/index.html in your browser to see the report. Continue to Deploy to Production.
1.5.10 Deploy to Production
This part of the tutorial assumes you have a server that you want to deploy your application to. It gives an overview of how to create the distribution file and install it, but won’t go into specifics about what server or software to use. You can set up a new environment on your development computer to try out the instructions below, but probably shouldn’t
1.5. Tutorial 51 Flask Documentation (1.1.x), Release 1.1.4
use it for hosting a real public application. See Deployment Options for a list of many different ways to host your application.
Build and Install
When you want to deploy your application elsewhere, you build a distribution file. The current standard for Python distribution is the wheel format, with the .whl extension. Make sure the wheel library is installed first:
$ pip install wheel
Running setup.py with Python gives you a command line tool to issue build-related commands. The bdist_wheel command will build a wheel distribution file.
$ python setup.py bdist_wheel
You can find the file in dist/flaskr-1.0.0-py3-none-any.whl. The file name is in the format of {project name}-{version}-{python tag} -{abi tag}-{platform tag}. Copy this file to another machine, set up a new virtualenv, then install the file with pip.
$ pip install flaskr-1.0.0-py3-none-any.whl
Pip will install your project along with its dependencies. Since this is a different machine, you need to run init-db again to create the database in the instance folder.
$ export FLASK_APP=flaskr $ flask init-db
When Flask detects that it’s installed (not in editable mode), it uses a different directory for the instance folder. You can find it at venv/var/flaskr-instance instead.
Configure the Secret Key
In the beginning of the tutorial that you gave a default value for SECRET_KEY. This should be changed to some random bytes in production. Otherwise, attackers could use the public 'dev' key to modify the session cookie, or anything else that uses the secret key. You can use the following command to output a random secret key:
$ python -c 'import os; print(os.urandom(16))'
b'_5#y2L"F4Q8z\n\xec]/'
Create the config.py file in the instance folder, which the factory will read from if it exists. Copy the generated value into it.
Listing 46: venv/var/flaskr-instance/config.py SECRET_KEY=b'_5#y2L"F4Q8z \n\xec]/'
You can also set any other necessary configuration here, although SECRET_KEY is the only one needed for Flaskr.
52 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Run with a Production Server
When running publicly rather than in development, you should not use the built-in development server (flask run). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure. Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:
$ pip install waitress
You need to tell Waitress about your application, but it doesn’t use FLASK_APP like flask run does. You need to tell it to import and call the application factory to get an application object.
$ waitress-serve --call 'flaskr:create_app'
Serving on http://0.0.0.0:8080
See Deployment Options for a list of many different ways to host your application. Waitress is just an example, chosen for the tutorial because it supports both Windows and Linux. There are many more WSGI servers and deployment options that you may choose for your project. Continue to Keep Developing!.
1.5.11 Keep Developing!
You’ve learned about quite a few Flask and Python concepts throughout the tutorial. Go back and review the tutorial and compare your code with the steps you took to get there. Compare your project to the example project, which might look a bit different due to the step-by-step nature of the tutorial. There’s a lot more to Flask than what you’ve seen so far. Even so, you’re now equipped to start developing your own web applications. Check out the Quickstart for an overview of what Flask can do, then dive into the docs to keep learning. Flask uses Jinja, Click, Werkzeug, and ItsDangerous behind the scenes, and they all have their own documentation too. You’ll also be interested in Extensions which make tasks like working with the database or validating form data easier and more powerful. If you want to keep developing your Flaskr project, here are some ideas for what to try next: • A detail view to show a single post. Click a post’s title to go to its page. • Like / unlike a post. • Comments. • Tags. Clicking a tag shows all the posts with that tag. • A search box that filters the index page by name. • Paged display. Only show 5 posts per page. • Upload an image to go along with a post. • Format posts using Markdown. • An RSS feed of new posts. Have fun and make awesome applications! This tutorial will walk you through creating a basic blog application called Flaskr. Users will be able to register, log in, create posts, and edit or delete their own posts. You will be able to package and install the application on other computers.
1.5. Tutorial 53 Flask Documentation (1.1.x), Release 1.1.4
It’s assumed that you’re already familiar with Python. The official tutorial in the Python docs is a great way to learn or review first. While it’s designed to give a good starting point, the tutorial doesn’t cover all of Flask’s features. Check out the Quickstart for an overview of what Flask can do, then dive into the docs to find out more. The tutorial only uses what’s provided by Flask and Python. In another project, you might decide to use Extensions or other libraries to make some tasks simpler.
54 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Flask is flexible. It doesn’t require you to use any particular project or code layout. However, when first starting, it’s helpful to use a more structured approach. This means that the tutorial will require a bit of boilerplate up front, but it’s done to avoid many common pitfalls that new developers encounter, and it creates a project that’s easy to expand on. Once you become more comfortable with Flask, you can step out of this structure and take full advantage of Flask’s flexibility.
1.5. Tutorial 55 Flask Documentation (1.1.x), Release 1.1.4
The tutorial project is available as an example in the Flask repository, if you want to compare your project with the final product as you follow the tutorial. Continue to Project Layout.
56 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.6 Templates
Flask leverages Jinja2 as its template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present. This section only gives a very quick introduction into how Jinja2 is integrated into Flask. If you want information on the template engine’s syntax itself, head over to the official Jinja2 Template Documentation for more information.
1.6.1 Jinja Setup
Unless customized, Jinja2 is configured by Flask as follows: • autoescaping is enabled for all templates ending in .html, .htm, .xml as well as .xhtml when using render_template(). • autoescaping is enabled for all strings when using render_template_string(). • a template has the ability to opt in/out autoescaping with the {% autoescape %} tag. • Flask inserts a couple of global functions and helpers into the Jinja2 context, additionally to the values that are present by default.
1.6.2 Standard Context
The following global variables are available within Jinja2 templates by default: config The current configuration object (flask.config) Changed in version 0.10: This is now always available, even in imported templates. New in version 0.6. request The current request object (flask.request). This variable is unavailable if the template was rendered without an active request context. session The current session object (flask.session). This variable is unavailable if the template was rendered without an active request context. g The request-bound object for global variables (flask.g). This variable is unavailable if the template was rendered without an active request context. url_for() The flask.url_for() function. get_flashed_messages() The flask.get_flashed_messages() function.
The Jinja Context Behavior These variables are added to the context of variables, they are not global variables. The difference is that by default these will not show up in the context of imported templates. This is partially caused by performance considerations, partially to keep things explicit.
1.6. Templates 57 Flask Documentation (1.1.x), Release 1.1.4
What does this mean for you? If you have a macro you want to import, that needs to access the request object you have two possibilities: 1. you explicitly pass the request to the macro as parameter, or the attribute of the request object you are interested in. 2. you import the macro “with context”. Importing with context looks like this:
{% from '_helpers.html' import my_macro with context %}
1.6.3 Standard Filters
Flask provides the following Jinja2 filters in addition to the filters provided by Jinja2 itself: tojson() This function converts the given object into JSON representation. This is for example very helpful if you try to generate JavaScript on the fly.
It is also safe to use the output of |tojson in a single-quoted HTML attribute:
Note that in versions of Flask prior to 0.10, if using the output of |tojson inside script, make sure to disable escaping with |safe. In Flask 0.10 and above, this happens automatically.
1.6.4 Controlling Autoescaping
Autoescaping is the concept of automatically escaping special characters for you. Special characters in the sense of HTML (or XML, and thus XHTML) are &, >, <, " as well as '. Because these characters carry specific meanings in documents on their own you have to replace them by so called “entities” if you want to use them for text. Not doing so would not only cause user frustration by the inability to use these characters in text, but can also lead to security problems. (see Cross-Site Scripting (XSS)) Sometimes however you will need to disable autoescaping in templates. This can be the case if you want to explicitly inject HTML into pages, for example if they come from a system that generates secure HTML like a markdown to HTML converter. There are three ways to accomplish that: • In the Python code, wrap the HTML string in a Markup object before passing it to the template. This is in general the recommended way. • Inside the template, use the |safe filter to explicitly mark a string as safe HTML ({{ myvariable|safe }}) • Temporarily disable the autoescape system altogether. To disable the autoescape system in templates, you can use the {% autoescape %} block:
58 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
{% autoescape false %}
autoescaping is disabled here
{{ will_not_be_escaped }} {% endautoescape %}
Whenever you do this, please be very cautious about the variables you are using in this block.
1.6.5 Registering Filters
If you want to register your own filters in Jinja2 you have two ways to do that. You can either put them by hand into the jinja_env of the application or use the template_filter() decorator. The two following examples work the same and both reverse an object:
@app.template_filter('reverse') def reverse_filter(s): return s[::-1]
def reverse_filter(s): return s[::-1] app.jinja_env.filters['reverse']= reverse_filter
In case of the decorator the argument is optional if you want to use the function name as name of the filter. Once registered, you can use the filter in your templates in the same way as Jinja2’s builtin filters, for example if you have a Python list in context called mylist:
{% for x in mylist| reverse%} {% endfor%}
1.6.6 Context Processors
To inject new variables automatically into the context of a template, context processors exist in Flask. Context pro- cessors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app:
@app.context_processor def inject_user(): return dict(user=g.user)
The context processor above makes a variable called user available in the template with the value of g.user. This example is not very interesting because g is available in templates anyways, but it gives an idea how this works. Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions):
@app.context_processor def utility_processor(): def format_price(amount, currency=u'C'): return u'{0:.2f}{1}'.format(amount, currency) return dict(format_price=format_price)
The context processor above makes the format_price function available to all templates:
1.6. Templates 59 Flask Documentation (1.1.x), Release 1.1.4
{{ format_price(0.33) }}
You could also build format_price as a template filter (see Registering Filters), but this demonstrates how to pass functions in a context processor.
1.7 Testing Flask Applications
Something that is untested is broken. The origin of this quote is unknown and while it is not entirely correct, it is also not far from the truth. Untested applications make it hard to improve existing code and developers of untested applications tend to become pretty paranoid. If an application has automated tests, you can safely make changes and instantly know if anything breaks. Flask provides a way to test your application by exposing the Werkzeug test Client and handling the context locals for you. You can then use that with your favourite testing solution. In this documentation we will use the pytest package as the base framework for our tests. You can install it with pip, like so:
$ pip install pytest
1.7.1 The Application
First, we need an application to test; we will use the application from the Tutorial. If you don’t have that application yet, get the source code from the examples.
1.7.2 The Testing Skeleton
We begin by adding a tests directory under the application root. Then create a Python file to store our tests (test_flaskr.py). When we format the filename like test_*.py, it will be auto-discoverable by pytest. Next, we create a pytest fixture called client() that configures the application for testing and initializes a new database: import os import tempfile import pytest from flaskr import flaskr
@pytest.fixture def client(): db_fd, flaskr.app.config['DATABASE']= tempfile.mkstemp() flaskr.app.config['TESTING']= True
with flaskr.app.test_client() as client: with flaskr.app.app_context(): flaskr.init_db() yield client
(continues on next page)
60 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) os.close(db_fd) os.unlink(flaskr.app.config['DATABASE'])
This client fixture will be called by each individual test. It gives us a simple interface to the application, where we can trigger test requests to the application. The client will also keep track of cookies for us. During setup, the TESTING config flag is activated. What this does is disable error catching during request handling, so that you get better error reports when performing test requests against the application. Because SQLite3 is filesystem-based, we can easily use the tempfile module to create a temporary database and initialize it. The mkstemp() function does two things for us: it returns a low-level file handle and a random file name, the latter we use as database name. We just have to keep the db_fd around so that we can use the os.close() function to close the file. To delete the database after the test, the fixture closes the file and removes it from the filesystem. If we now run the test suite, we should see the following output:
$ pytest
======test session starts ======rootdir: ./flask/examples/flaskr, inifile: setup.cfg collected 0 items
======no tests ran in 0.07 seconds ======
Even though it did not run any actual tests, we already know that our flaskr application is syntactically valid, otherwise the import would have died with an exception.
1.7.3 The First Test
Now it’s time to start testing the functionality of the application. Let’s check that the application shows “No entries here so far” if we access the root of the application (/). To do this, we add a new test function to test_flaskr.py, like this:
def test_empty_db(client): """Start with a blank database."""
rv= client.get('/') assert b'No entries here so far' in rv.data
Notice that our test functions begin with the word test; this allows pytest to automatically identify the function as a test to run. By using client.get we can send an HTTP GET request to the application with the given path. The return value will be a response_class object. We can now use the data attribute to inspect the return value (as string) from the application. In this case, we ensure that 'No entries here so far' is part of the output. Run it again and you should see one passing test:
$ pytest -v
======test session starts ======rootdir: ./flask/examples/flaskr, inifile: setup.cfg collected 1 items
(continues on next page)
1.7. Testing Flask Applications 61 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) tests/test_flaskr.py::test_empty_db PASSED
======1 passed in 0.10 seconds ======
1.7.4 Logging In and Out
The majority of the functionality of our application is only available for the administrative user, so we need a way to log our test client in and out of the application. To do this, we fire some requests to the login and logout pages with the required form data (username and password). And because the login and logout pages redirect, we tell the client to follow_redirects. Add the following two functions to your test_flaskr.py file: def login(client, username, password): return client.post('/login', data=dict( username=username, password=password ), follow_redirects=True) def logout(client): return client.get('/logout', follow_redirects=True)
Now we can easily test that logging in and out works and that it fails with invalid credentials. Add this new test function: def test_login_logout(client): """Make sure login and logout works."""
rv= login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']) assert b'You were logged in' in rv.data
rv= logout(client) assert b'You were logged out' in rv.data
rv= login(client, flaskr.app.config['USERNAME']+'x', flaskr.app.config[
˓→'PASSWORD']) assert b'Invalid username' in rv.data
rv= login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']+
˓→'x') assert b'Invalid password' in rv.data
1.7.5 Test Adding Messages
We should also test that adding messages works. Add a new test function like this: def test_messages(client): """Test that messages work."""
login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD']) rv= client.post('/add', data=dict( title='
62 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) text='HTML allowed here' ), follow_redirects=True) assert b'No entries here so far' not in rv.data assert b'<Hello>' in rv.data assert b'HTML allowed here' in rv.data
Here we check that HTML is allowed in the text but not in the title, which is the intended behavior. Running that should now give us three passing tests:
$ pytest -v
======test session starts ======rootdir: ./flask/examples/flaskr, inifile: setup.cfg collected 3 items tests/test_flaskr.py::test_empty_db PASSED tests/test_flaskr.py::test_login_logout PASSED tests/test_flaskr.py::test_messages PASSED
======3 passed in 0.23 seconds ======
1.7.6 Other Testing Tricks
Besides using the test client as shown above, there is also the test_request_context() method that can be used in combination with the with statement to activate a request context temporarily. With this you can access the request, g and session objects like in view functions. Here is a full example that demonstrates this approach: import flask app= flask.Flask(__name__) with app.test_request_context('/?name=Peter'): assert flask.request.path =='/' assert flask.request.args['name'] =='Peter'
All the other objects that are context bound can be used in the same way. If you want to test your application with different configurations and there does not seem to be a good way to do that, consider switching to application factories (see Application Factories). Note however that if you are using a test request context, the before_request() and after_request() functions are not called automatically. However teardown_request() functions are indeed executed when the test request context leaves the with block. If you do want the before_request() functions to be called as well, you need to call preprocess_request() yourself: app= flask.Flask(__name__) with app.test_request_context('/?name=Peter'): app.preprocess_request() ...
This can be necessary to open database connections or something similar depending on how your application was designed.
1.7. Testing Flask Applications 63 Flask Documentation (1.1.x), Release 1.1.4
If you want to call the after_request() functions you need to call into process_response() which however requires that you pass it a response object:
app= flask.Flask(__name__)
with app.test_request_context('/?name=Peter'): resp= Response('...') resp= app.process_response(resp) ...
This in general is less useful because at that point you can directly start using the test client.
1.7.7 Faking Resources and Context
New in version 0.10. A very common pattern is to store user authorization information and database connections on the application context or the flask.g object. The general pattern for this is to put the object on there on first usage and then to remove it on a teardown. Imagine for instance this code to get the current user:
def get_user(): user= getattr(g,'user', None) if user is None: user= fetch_current_user_from_database() g.user= user return user
For a test it would be nice to override this user from the outside without having to change some code. This can be accomplished with hooking the flask.appcontext_pushed signal:
from contextlib import contextmanager from flask import appcontext_pushed, g
@contextmanager def user_set(app, user): def handler(sender, **kwargs): g.user= user with appcontext_pushed.connected_to(handler, app): yield
And then to use it:
from flask import json, jsonify
@app.route('/users/me') def users_me(): return jsonify(username=g.user.username) with user_set(app, my_user): with app.test_client() as c: resp=c.get('/users/me') data= json.loads(resp.data) self.assert_equal(data['username'], my_user.username)
64 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.7.8 Keeping the Context Around
New in version 0.4. Sometimes it is helpful to trigger a regular request but still keep the context around for a little longer so that additional introspection can happen. With Flask 0.4 this is possible by using the test_client() with a with block:
app= flask.Flask(__name__)
with app.test_client() as c: rv=c.get('/?tequila=42') assert request.args['tequila'] =='42'
If you were to use just the test_client() without the with block, the assert would fail with an error because request is no longer available (because you are trying to use it outside of the actual request).
1.7.9 Accessing and Modifying Sessions
New in version 0.8. Sometimes it can be very helpful to access or modify the sessions from the test client. Generally there are two ways for this. If you just want to ensure that a session has certain keys set to certain values you can just keep the context around and access flask.session:
with app.test_client() as c: rv=c.get('/') assert flask.session['foo'] == 42
This however does not make it possible to also modify the session or to access the session before a request was fired. Starting with Flask 0.8 we provide a so called “session transaction” which simulates the appropriate calls to open a session in the context of the test client and to modify it. At the end of the transaction the session is stored and ready to be used by the test client. This works independently of the session backend used:
with app.test_client() as c: with c.session_transaction() as sess: sess['a_key']='a value'
# once this is reached the session was stored and ready to be used by the client c.get(...)
Note that in this case you have to use the sess object instead of the flask.session proxy. The object however itself will provide the same interface.
1.7.10 Testing JSON APIs
New in version 1.0. Flask has great support for JSON, and is a popular choice for building JSON APIs. Making requests with JSON data and examining JSON data in responses is very convenient:
from flask import request, jsonify
@app.route('/api/auth') def auth(): json_data= request.get_json() (continues on next page)
1.7. Testing Flask Applications 65 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) email= json_data['email'] password= json_data['password'] return jsonify(token=generate_token(email, password))
with app.test_client() as c: rv=c.post('/api/auth', json={ 'email':'flask@example.com','password':'secret' }) json_data= rv.get_json() assert verify_token(email, json_data['token'])
Passing the json argument in the test client methods sets the request data to the JSON-serialized object and sets the content type to application/json. You can get the JSON data from the request or response with get_json.
1.7.11 Testing CLI Commands
Click comes with utilities for testing your CLI commands. A CliRunner runs commands in isolation and captures the output in a Result object. Flask provides test_cli_runner() to create a FlaskCliRunner that passes the Flask app to the CLI auto- matically. Use its invoke() method to call commands in the same way they would be called from the command line.
import click
@app.cli.command('hello') @click.option('--name', default='World') def hello_command(name): click.echo(f'Hello, {name}!') def test_hello(): runner= app.test_cli_runner()
# invoke the command directly result= runner.invoke(hello_command, ['--name','Flask']) assert 'Hello, Flask' in result.output
# or by name result= runner.invoke(args=['hello']) assert 'World' in result.output
In the example above, invoking the command by name is useful because it verifies that the command was correctly registered with the app. If you want to test how your command parses parameters, without running the command, use its make_context() method. This is useful for testing complex validation rules and custom types.
def upper(ctx, param, value): if value is not None: return value.upper()
@app.cli.command('hello') @click.option('--name', default='World', callback=upper) def hello_command(name): click.echo(f'Hello, {name}!') (continues on next page)
66 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def test_hello_params(): context= hello_command.make_context('hello',['--name','flask']) assert context.params['name'] =='FLASK'
1.8 Application Errors
New in version 0.3. Applications fail, servers fail. Sooner or later you will see an exception in production. Even if your code is 100% correct, you will still see exceptions from time to time. Why? Because everything else involved will fail. Here are some situations where perfectly fine code can lead to server errors: • the client terminated the request early and the application was still reading from the incoming data • the database server was overloaded and could not handle the query • a filesystem is full • a harddrive crashed • a backend server overloaded • a programming error in a library you are using • network connection of the server to another system failed And that’s just a small sample of issues you could be facing. So how do we deal with that sort of problem? By default if your application runs in production mode, Flask will display a very simple page for you and log the exception to the logger. But there is more you can do, and we will cover some better setups to deal with errors.
1.8.1 Error Logging Tools
Sending error mails, even if just for critical ones, can become overwhelming if enough users are hitting the error and log files are typically never looked at. This is why we recommend using Sentry for dealing with application errors. It’s available as an Open Source project on GitHub and is also available as a hosted version which you can try for free. Sentry aggregates duplicate errors, captures the full stack trace and local variables for debugging, and sends you mails based on new errors or frequency thresholds. To use Sentry you need to install the sentry-sdk client with extra flask dependencies:
$ pip install sentry-sdk[flask]
And then add this to your Flask app: import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])
The YOUR_DSN_HERE value needs to be replaced with the DSN value you get from your Sentry installation. After installation, failures leading to an Internal Server Error are automatically reported to Sentry and from there you can receive error notifications.
1.8. Application Errors 67 Flask Documentation (1.1.x), Release 1.1.4
Follow-up reads: • Sentry also supports catching errors from your worker queue (RQ, Celery) in a similar fashion. See the Python SDK docs for more information. • Getting started with Sentry • Flask-specific documentation.
1.8.2 Error handlers
You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers. An error handler is a normal view function that returns a response, but instead of being registered for a route, it is registered for an exception or HTTP status code that would be raised while trying to handle a request.
Registering
Register handlers by decorating a function with errorhandler(). Or use register_error_handler() to register the function later. Remember to set the error code when returning the response.
@app.errorhandler(werkzeug.exceptions.BadRequest) def handle_bad_request(e): return 'bad request!', 400
# or, without the decorator app.register_error_handler(400, handle_bad_request) werkzeug.exceptions.HTTPException subclasses like BadRequest and their HTTP codes are inter- changeable when registering handlers. (BadRequest.code == 400) Non-standard HTTP codes cannot be registered by code because they are not known by Werkzeug. Instead, define a subclass of HTTPException with the appropriate code and register and raise that exception class. class InsufficientStorage(werkzeug.exceptions.HTTPException): code= 507 description='Not enough storage space.' app.register_error_handler(InsufficientStorage, handle_507) raise InsufficientStorage()
Handlers can be registered for any exception class, not just HTTPException subclasses or HTTP status codes. Handlers can be registered for a specific class, or for all subclasses of a parent class.
Handling
When an exception is caught by Flask while handling a request, it is first looked up by code. If no handler is registered for the code, it is looked up by its class hierarchy; the most specific handler is chosen. If no handler is registered, HTTPException subclasses show a generic message about their code, while other exceptions are converted to a generic 500 Internal Server Error. For example, if an instance of ConnectionRefusedError is raised, and a handler is registered for ConnectionError and ConnectionRefusedError, the more specific ConnectionRefusedError han- dler is called with the exception instance to generate the response.
68 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Handlers registered on the blueprint take precedence over those registered globally on the application, assuming a blueprint is handling the request that raises the exception. However, the blueprint cannot handle 404 routing errors because the 404 occurs at the routing level before the blueprint can be determined.
Generic Exception Handlers
It is possible to register error handlers for very generic base classes such as HTTPException or even Exception. However, be aware that these will catch more than you might expect. An error handler for HTTPException might be useful for turning the default HTML errors pages into JSON, for example. However, this handler will trigger for things you don’t cause directly, such as 404 and 405 errors during routing. Be sure to craft your handler carefully so you don’t lose information about the HTTP error.
from flask import json from werkzeug.exceptions import HTTPException
@app.errorhandler(HTTPException) def handle_exception(e): """Return JSON instead of HTML for HTTP errors.""" # start with the correct headers and status code from the error response=e.get_response() # replace the body with JSON response.data= json.dumps({ "code": e.code, "name": e.name, "description": e.description, }) response.content_type="application/json" return response
An error handler for Exception might seem useful for changing how all errors, even unhandled ones, are presented to the user. However, this is similar to doing except Exception: in Python, it will capture all otherwise un- handled errors, including all HTTP status codes. In most cases it will be safer to register handlers for more specific exceptions. Since HTTPException instances are valid WSGI responses, you could also pass them through directly.
from werkzeug.exceptions import HTTPException
@app.errorhandler(Exception) def handle_exception(e): # pass through HTTP errors if isinstance(e, HTTPException): return e
# now you're handling non-HTTP exceptions only return render_template("500_generic.html", e=e), 500
Error handlers still respect the exception class hierarchy. If you register handlers for both HTTPException and Exception, the Exception handler will not handle HTTPException subclasses because it the HTTPException handler is more specific.
Unhandled Exceptions
When there is no error handler registered for an exception, a 500 Internal Server Error will be returned instead. See flask.Flask.handle_exception() for information about this behavior.
1.8. Application Errors 69 Flask Documentation (1.1.x), Release 1.1.4
If there is an error handler registered for InternalServerError, this will be invoked. As of Flask 1.1.0, this error handler will always be passed an instance of InternalServerError, not the original unhandled error. The original error is available as e.original_exception. Until Werkzeug 1.0.0, this attribute will only exist during unhandled errors, use getattr to get access it for compatibility.
@app.errorhandler(InternalServerError) def handle_500(e): original= getattr(e,"original_exception", None)
if original is None: # direct 500 error, such as abort(500) return render_template("500.html"), 500
# wrapped unhandled error return render_template("500_unhandled.html", e=original), 500
1.8.3 Logging
See Logging for information on how to log exceptions, such as by emailing them to admins.
1.9 Debugging Application Errors
For production applications, configure your application with logging and notifications as described in Application Errors. This section provides pointers when debugging deployment configuration and digging deeper with a full- featured Python debugger.
1.9.1 When in Doubt, Run Manually
Having problems getting your application configured for production? If you have shell access to your host, verify that you can run your application manually from the shell in the deployment environment. Be sure to run under the same user account as the configured deployment to troubleshoot permission issues. You can use Flask’s builtin development server with debug=True on your production host, which is helpful in catching configuration issues, but be sure to do this temporarily in a controlled environment. Do not run in production with debug=True.
1.9.2 Working with Debuggers
To dig deeper, possibly to trace code execution, Flask provides a debugger out of the box (see Debug Mode). If you would like to use another Python debugger, note that debuggers interfere with each other. You have to set some options in order to use your favorite debugger: • debug - whether to enable debug mode and catch exceptions • use_debugger - whether to use the internal Flask debugger • use_reloader - whether to reload and fork the process if modules were changed debug must be True (i.e., exceptions must be caught) in order for the other two options to have any value. If you’re using Aptana/Eclipse for debugging you’ll need to set both use_debugger and use_reloader to False. A possible useful pattern for configuration is to set the following in your config.yaml (change the block as appropriate for your application, of course):
70 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
FLASK: DEBUG: True DEBUG_WITH_APTANA: True
Then in your application’s entry-point (main.py), you could have something like: if __name__ =="__main__": # To allow aptana to receive errors, set use_debugger=False app= create_app(config="config.yaml")
use_debugger= app.debug and not(app.config.get('DEBUG_WITH_APTANA')) app.run(use_debugger=use_debugger, debug=app.debug, use_reloader=use_debugger, host='0.0.0.0')
1.10 Logging
Flask uses standard Python logging. Messages about your Flask application are logged with app.logger, which takes the same name as app.name. This logger can also be used to log your own messages.
@app.route('/login', methods=['POST']) def login(): user= get_user(request.form['username'])
if user.check_password(request.form['password']): login_user(user) app.logger.info('%s logged in successfully', user.username) return redirect(url_for('index')) else: app.logger.info('%s failed to log in', user.username) abort(401)
1.10.1 Basic Configuration
When you want to configure logging for your project, you should do it as soon as possible when the program starts. If app.logger is accessed before logging is configured, it will add a default handler. If possible, configure logging before creating the application object. This example uses dictConfig() to create a logging configuration similar to Flask’s default, except for all logs: from logging.config import dictConfig dictConfig({ 'version':1, 'formatters':{'default':{ 'format':'[ %(asctime)s] %(levelname)s in %(module)s: %(message)s', }}, 'handlers':{'wsgi':{ 'class':'logging.StreamHandler', 'stream':'ext://flask.logging.wsgi_errors_stream', 'formatter':'default' }}, 'root':{ 'level':'INFO', (continues on next page)
1.10. Logging 71 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) 'handlers':['wsgi'] } }) app= Flask(__name__)
Default Configuration
If you do not configure logging yourself, Flask will add a StreamHandler to app.logger automatically. During requests, it will write to the stream specified by the WSGI server in environ['wsgi.errors'] (which is usually sys.stderr). Outside a request, it will log to sys.stderr.
Removing the Default Handler
If you configured logging after accessing app.logger, and need to remove the default handler, you can import and remove it: from flask.logging import default_handler app.logger.removeHandler(default_handler)
1.10.2 Email Errors to Admins
When running the application on a remote server for production, you probably won’t be looking at the log messages very often. The WSGI server will probably send log messages to a file, and you’ll only check that file if a user tells you something went wrong. To be proactive about discovering and fixing bugs, you can configure a logging.handlers.SMTPHandler to send an email when errors and higher are logged. import logging from logging.handlers import SMTPHandler mail_handler= SMTPHandler( mailhost='127.0.0.1', fromaddr='server-error@example.com', toaddrs=['admin@example.com'], subject='Application Error' ) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(logging.Formatter( '[%(asctime)s] %(levelname)s in %(module)s: %(message)s' )) if not app.debug: app.logger.addHandler(mail_handler)
This requires that you have an SMTP server set up on the same server. See the Python docs for more information about configuring the handler.
72 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.10.3 Injecting Request Information
Seeing more information about the request, such as the IP address, may help debugging some errors. You can subclass logging.Formatter to inject your own fields that can be used in messages. You can change the formatter for Flask’s default handler, the mail handler defined above, or any other handler.
from flask import has_request_context, request from flask.logging import default_handler
class RequestFormatter(logging.Formatter): def format(self, record): if has_request_context(): record.url= request.url record.remote_addr= request.remote_addr else: record.url= None record.remote_addr= None
return super().format(record)
formatter= RequestFormatter( '[%(asctime)s] %(remote_addr)s requested %(url)s\n' '%(levelname)s in %(module)s: %(message)s' ) default_handler.setFormatter(formatter) mail_handler.setFormatter(formatter)
1.10.4 Other Libraries
Other libraries may use logging extensively, and you want to see relevant messages from those logs too. The simplest way to do this is to add handlers to the root logger instead of only the app logger.
from flask.logging import default_handler
root= logging.getLogger() root.addHandler(default_handler) root.addHandler(mail_handler)
Depending on your project, it may be more useful to configure each logger you care about separately, instead of configuring only the root logger.
for logger in ( app.logger, logging.getLogger('sqlalchemy'), logging.getLogger('other_package'), ): logger.addHandler(default_handler) logger.addHandler(mail_handler)
Werkzeug
Werkzeug logs basic request/response information to the 'werkzeug' logger. If the root logger has no handlers configured, Werkzeug adds a StreamHandler to its logger.
1.10. Logging 73 Flask Documentation (1.1.x), Release 1.1.4
Flask Extensions
Depending on the situation, an extension may choose to log to app.logger or its own named logger. Consult each extension’s documentation for details.
1.11 Configuration Handling
Applications need some kind of configuration. There are different settings you might want to change depending on the application environment like toggling the debug mode, setting the secret key, and other such environment-specific things. The way Flask is designed usually requires the configuration to be available when the application starts up. You can hard code the configuration in the code, which for many small applications is not actually that bad, but there are better ways. Independent of how you load your config, there is a config object available which holds the loaded configuration values: The config attribute of the Flask object. This is the place where Flask itself puts certain configuration values and also where extensions can put their configuration values. But this is also where you can have your own configuration.
1.11.1 Configuration Basics
The config is actually a subclass of a dictionary and can be modified just like any dictionary:
app= Flask(__name__) app.config['TESTING']= True
Certain configuration values are also forwarded to the Flask object so you can read and write them from there:
app.testing= True
To update multiple keys at once you can use the dict.update() method:
app.config.update( TESTING=True, SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/' )
1.11.2 Environment and Debug Features
The ENV and DEBUG config values are special because they may behave inconsistently if changed after the app has begun setting up. In order to set the environment and debug mode reliably, Flask uses environment variables. The environment is used to indicate to Flask, extensions, and other programs, like Sentry, what context Flask is running in. It is controlled with the FLASK_ENV environment variable and defaults to production. Setting FLASK_ENV to development will enable debug mode. flask run will use the interactive debugger and reloader by default in debug mode. To control this separately from the environment, use the FLASK_DEBUG flag. Changed in version 1.0: Added FLASK_ENV to control the environment separately from debug mode. The develop- ment environment enables debug mode. To switch Flask to the development environment and enable debug mode, set FLASK_ENV:
74 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
$ export FLASK_ENV=development $ flask run
(On Windows, use set instead of export.) Using the environment variables as described above is recommended. While it is possible to set ENV and DEBUG in your config or code, this is strongly discouraged. They can’t be read early by the flask command, and some systems or extensions may have already configured themselves based on a previous value.
1.11.3 Builtin Configuration Values
The following configuration values are used internally by Flask: ENV What environment the app is running in. Flask and extensions may enable behaviors based on the environment, such as enabling debug mode. The env attribute maps to this config key. This is set by the FLASK_ENV environment variable and may not behave as expected if set in code. Do not enable development when deploying in production. Default: 'production' New in version 1.0. DEBUG Whether debug mode is enabled. When using flask run to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. The debug attribute maps to this config key. This is enabled when ENV is 'development' and is overridden by the FLASK_DEBUG environment variable. It may not behave as expected if set in code. Do not enable debug mode when deploying in production. Default: True if ENV is 'development', or False otherwise. TESTING Enable testing mode. Exceptions are propagated rather than handled by the the app’s error handlers. Extensions may also change their behavior to facilitate easier testing. You should enable this in your own tests. Default: False PROPAGATE_EXCEPTIONS Exceptions are re-raised rather than being handled by the app’s error handlers. If not set, this is implicitly true if TESTING or DEBUG is enabled. Default: None PRESERVE_CONTEXT_ON_EXCEPTION Don’t pop the request context when an exception occurs. If not set, this is true if DEBUG is true. This allows debuggers to introspect the request data on errors, and should normally not need to be set directly. Default: None TRAP_HTTP_EXCEPTIONS If there is no handler for an HTTPException-type exception, re-raise it to be handled by the interactive debugger instead of returning it as a simple error response. Default: False TRAP_BAD_REQUEST_ERRORS Trying to access a key that doesn’t exist from request dicts like args and form will return a 400 Bad Request error page. Enable this to treat the error as an unhandled exception instead so that you get the interactive
1.11. Configuration Handling 75 Flask Documentation (1.1.x), Release 1.1.4
debugger. This is a more specific version of TRAP_HTTP_EXCEPTIONS. If unset, it is enabled in debug mode. Default: None SECRET_KEY A secret key that will be used for securely signing the session cookie and can be used for any other security related needs by extensions or your application. It should be a long random string of bytes, although unicode is accepted too. For example, copy the output of this to your config:
$ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/'
Do not reveal the secret key when posting questions or committing code. Default: None SESSION_COOKIE_NAME The name of the session cookie. Can be changed in case you already have a cookie with the same name. Default: 'session' SESSION_COOKIE_DOMAIN The domain match rule that the session cookie will be valid for. If not set, the cookie will be valid for all subdomains of SERVER_NAME. If False, the cookie’s domain will not be set. Default: None SESSION_COOKIE_PATH The path that the session cookie will be valid for. If not set, the cookie will be valid underneath APPLICATION_ROOT or / if that is not set. Default: None SESSION_COOKIE_HTTPONLY Browsers will not allow JavaScript access to cookies marked as “HTTP only” for security. Default: True SESSION_COOKIE_SECURE Browsers will only send cookies with requests over HTTPS if the cookie is marked “secure”. The application must be served over HTTPS for this to make sense. Default: False SESSION_COOKIE_SAMESITE Restrict how cookies are sent with requests from external sites. Can be set to 'Lax' (recommended) or 'Strict'. See Set-Cookie options. Default: None New in version 1.0. PERMANENT_SESSION_LIFETIME If session.permanent is true, the cookie’s expiration will be set this number of seconds in the future. Can either be a datetime.timedelta or an int. Flask’s default cookie implementation validates that the cryptographic signature is not older than this value. Default: timedelta(days=31) (2678400 seconds) SESSION_REFRESH_EACH_REQUEST Control whether the cookie is sent with every response when session.permanent is true. Sending the
76 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
cookie every time (the default) can more reliably keep the session from expiring, but uses more bandwidth. Non-permanent sessions are not affected. Default: True USE_X_SENDFILE When serving files, set the X-Sendfile header instead of serving the data with Flask. Some web servers, such as Apache, recognize this and serve the data more efficiently. This only makes sense when using such a server. Default: False SEND_FILE_MAX_AGE_DEFAULT When serving files, set the cache control max age to this number of seconds. Can either be a datetime. timedelta or an int. Override this value on a per-file basis using get_send_file_max_age() on the application or blueprint. Default: timedelta(hours=12) (43200 seconds) SERVER_NAME Inform the application what host and port it is bound to. Required for subdomain route matching support. If set, will be used for the session cookie domain if SESSION_COOKIE_DOMAIN is not set. Modern web browsers will not allow setting cookies for domains without a dot. To use a domain locally, add any names that should route to the app to your hosts file.
127.0.0.1 localhost.dev
If set, url_for can generate external URLs with only an application context instead of a request context. Default: None APPLICATION_ROOT Inform the application what path it is mounted under by the application / web server. This is used for generating URLs outside the context of a request (inside a request, the dispatcher is responsible for setting SCRIPT_NAME instead; see Application Dispatching for examples of dispatch configuration). Will be used for the session cookie path if SESSION_COOKIE_PATH is not set. Default: '/' PREFERRED_URL_SCHEME Use this scheme for generating external URLs when not in a request context. Default: 'http' MAX_CONTENT_LENGTH Don’t read more than this many bytes from the incoming request data. If not set and the request does not specify a CONTENT_LENGTH, no data will be read for security. Default: None JSON_AS_ASCII Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON will be returned as a Unicode string, or encoded as UTF-8 by jsonify. This has security implications when rendering the JSON into JavaScript in templates, and should typically remain enabled. Default: True JSON_SORT_KEYS Sort the keys of JSON objects alphabetically. This is useful for caching because it ensures the data is serialized the same way no matter what Python’s hash seed is. While not recommended, you can disable this for a possible performance improvement at the cost of caching.
1.11. Configuration Handling 77 Flask Documentation (1.1.x), Release 1.1.4
Default: True JSONIFY_PRETTYPRINT_REGULAR jsonify responses will be output with newlines, spaces, and indentation for easier reading by humans. Always enabled in debug mode. Default: False JSONIFY_MIMETYPE The mimetype of jsonify responses. Default: 'application/json' TEMPLATES_AUTO_RELOAD Reload templates when they are changed. If not set, it will be enabled in debug mode. Default: None EXPLAIN_TEMPLATE_LOADING Log debugging information tracing how a template file was loaded. This can be useful to figure out why a template was not loaded or the wrong file appears to be loaded. Default: False MAX_COOKIE_SIZE Warn if cookie headers are larger than this many bytes. Defaults to 4093. Larger cookies may be silently ignored by browsers. Set to 0 to disable the warning. Changed in version 1.0: LOGGER_NAME and LOGGER_HANDLER_POLICY were removed. See Logging for infor- mation about configuration. Added ENV to reflect the FLASK_ENV environment variable. Added SESSION_COOKIE_SAMESITE to control the session cookie’s SameSite option. Added MAX_COOKIE_SIZE to control a warning from Werkzeug. New in version 0.11: SESSION_REFRESH_EACH_REQUEST, TEMPLATES_AUTO_RELOAD, LOGGER_HANDLER_POLICY, EXPLAIN_TEMPLATE_LOADING New in version 0.10: JSON_AS_ASCII, JSON_SORT_KEYS, JSONIFY_PRETTYPRINT_REGULAR New in version 0.9: PREFERRED_URL_SCHEME New in version 0.8: TRAP_BAD_REQUEST_ERRORS, TRAP_HTTP_EXCEPTIONS, APPLICATION_ROOT, SESSION_COOKIE_DOMAIN, SESSION_COOKIE_PATH, SESSION_COOKIE_HTTPONLY, SESSION_COOKIE_SECURE New in version 0.7: PROPAGATE_EXCEPTIONS, PRESERVE_CONTEXT_ON_EXCEPTION New in version 0.6: MAX_CONTENT_LENGTH New in version 0.5: SERVER_NAME New in version 0.4: LOGGER_NAME
1.11.4 Configuring from Files
Configuration becomes more useful if you can store it in a separate file, ideally located outside the actual applica- tion package. This makes packaging and distributing your application possible via various package handling tools (Deploying with Setuptools) and finally modifying the configuration file afterwards. So a common pattern is this:
78 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
app= Flask(__name__) app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS')
This first loads the configuration from the yourapplication.default_settings module and then overrides the values with the contents of the file the YOURAPPLICATION_SETTINGS environment variable points to. This environment variable can be set on Linux or OS X with the export command in the shell before starting the server:
$ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg $ python run-app.py * Running on http://127.0.0.1:5000/ * Restarting with reloader...
On Windows systems use the set builtin instead:
> set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
The configuration files themselves are actual Python files. Only values in uppercase are actually stored in the config object later on. So make sure to use uppercase letters for your config keys. Here is an example of a configuration file:
# Example configuration DEBUG= False SECRET_KEY=b'_5#y2L"F4Q8z \n\xec]/'
Make sure to load the configuration very early on, so that extensions have the ability to access the configuration when starting up. There are other methods on the config object as well to load from individual files. For a complete reference, read the Config object’s documentation.
1.11.5 Configuring from Environment Variables
In addition to pointing to configuration files using environment variables, you may find it useful (or necessary) to control your configuration values directly from the environment. Environment variables can be set on Linux or OS X with the export command in the shell before starting the server:
$ export SECRET_KEY='5f352379324c22463451387a0aec5d2f' $ export MAIL_ENABLED=false $ python run-app.py * Running on http://127.0.0.1:5000/
On Windows systems use the set builtin instead:
> set SECRET_KEY='5f352379324c22463451387a0aec5d2f'
While this approach is straightforward to use, it is important to remember that environment variables are strings – they are not automatically deserialized into Python types. Here is an example of a configuration file that uses environment variables: import os
_mail_enabled= os.environ.get("MAIL_ENABLED", default="true") MAIL_ENABLED= _mail_enabled.lower() in {"1","t","true"}
(continues on next page)
1.11. Configuration Handling 79 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) SECRET_KEY= os.environ.get("SECRET_KEY")
if not SECRET_KEY: raise ValueError("No SECRET_KEY set for Flask application")
Notice that any value besides an empty string will be interpreted as a boolean True value in Python, which requires care if an environment explicitly sets values intended to be False. Make sure to load the configuration very early on, so that extensions have the ability to access the configuration when starting up. There are other methods on the config object as well to load from individual files. For a complete reference, read the Config class documentation.
1.11.6 Configuration Best Practices
The downside with the approach mentioned earlier is that it makes testing a little harder. There is no single 100% solution for this problem in general, but there are a couple of things you can keep in mind to improve that experience: 1. Create your application in a function and register blueprints on it. That way you can create multiple instances of your application with different configurations attached which makes unit testing a lot easier. You can use this to pass in configuration as needed. 2. Do not write code that needs the configuration at import time. If you limit yourself to request-only accesses to the configuration you can reconfigure the object later on as needed.
1.11.7 Development / Production
Most applications need more than one configuration. There should be at least separate configurations for the production server and the one used during development. The easiest way to handle this is to use a default configuration that is always loaded and part of the version control, and a separate configuration that overrides the values as necessary as mentioned in the example above:
app= Flask(__name__) app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS')
Then you just have to add a separate config.py file and export YOURAPPLICATION_SETTINGS=/path/to/ config.py and you are done. However there are alternative ways as well. For example you could use imports or subclassing. What is very popular in the Django world is to make the import explicit in the config file by adding from yourapplication.default_settings import * to the top of the file and then overriding the changes by hand. You could also inspect an environment variable like YOURAPPLICATION_MODE and set that to production, development etc and import different hard-coded files based on that. An interesting pattern is also to use classes and inheritance for configuration:
class Config(object): DEBUG= False TESTING= False DATABASE_URI='sqlite:///:memory:'
class ProductionConfig(Config): DATABASE_URI='mysql://user@localhost/foo'
(continues on next page)
80 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) class DevelopmentConfig(Config): DEBUG= True class TestingConfig(Config): TESTING= True
To enable such a config you just have to call into from_object(): app.config.from_object('configmodule.ProductionConfig')
Note that from_object() does not instantiate the class object. If you need to instantiate the class, such as to access a property, then you must do so before calling from_object(): from configmodule import ProductionConfig app.config.from_object(ProductionConfig())
# Alternatively, import via string: from werkzeug.utils import import_string cfg= import_string('configmodule.ProductionConfig')() app.config.from_object(cfg)
Instantiating the configuration object allows you to use @property in your configuration classes: class Config(object): """Base config, uses staging database server.""" DEBUG= False TESTING= False DB_SERVER='192.168.1.56'
@property def DATABASE_URI(self): # Note: all caps return 'mysql://user@{}/foo'.format(self.DB_SERVER) class ProductionConfig(Config): """Uses production database server.""" DB_SERVER='192.168.19.32' class DevelopmentConfig(Config): DB_SERVER='localhost' DEBUG= True class TestingConfig(Config): DB_SERVER='localhost' DEBUG= True DATABASE_URI='sqlite:///:memory:'
There are many different ways and it’s up to you how you want to manage your configuration files. However here a list of good recommendations: • Keep a default configuration in version control. Either populate the config with this default configuration or import it in your own configuration files before overriding values. • Use an environment variable to switch between the configurations. This can be done from outside the Python interpreter and makes development and deployment much easier because you can quickly and easily switch between different configs without having to touch the code at all. If you are working often on different projects you can even create your own script for sourcing that activates a virtualenv and exports the development config- uration for you.
1.11. Configuration Handling 81 Flask Documentation (1.1.x), Release 1.1.4
• Use a tool like fabric in production to push code and configurations separately to the production server(s). For some details about how to do that, head over to the Deploying with Fabric pattern.
1.11.8 Instance Folders
New in version 0.8. Flask 0.8 introduces instance folders. Flask for a long time made it possible to refer to paths relative to the application’s folder directly (via Flask.root_path). This was also how many developers loaded configurations stored next to the application. Unfortunately however this only works well if applications are not packages in which case the root path refers to the contents of the package. With Flask 0.8 a new attribute was introduced: Flask.instance_path. It refers to a new concept called the “instance folder”. The instance folder is designed to not be under version control and be deployment specific. It’s the perfect place to drop things that either change at runtime or configuration files. You can either explicitly provide the path of the instance folder when creating the Flask application or you can let Flask autodetect the instance folder. For explicit configuration use the instance_path parameter:
app= Flask(__name__, instance_path='/path/to/instance/folder')
Please keep in mind that this path must be absolute when provided. If the instance_path parameter is not provided the following default locations are used: • Uninstalled module:
/myapp.py /instance
• Uninstalled package:
/myapp /__init__.py /instance
• Installed module or package:
$PREFIX/lib/python2.X/site-packages/myapp $PREFIX/var/myapp-instance
$PREFIX is the prefix of your Python installation. This can be /usr or the path to your virtualenv. You can print the value of sys.prefix to see what the prefix is set to. Since the config object provided loading of configuration files from relative filenames we made it possible to change the loading via filenames to be relative to the instance path if wanted. The behavior of relative paths in config files can be flipped between “relative to the application root” (the default) to “relative to instance folder” via the instance_relative_config switch to the application constructor:
app= Flask(__name__, instance_relative_config= True)
Here is a full example of how to configure Flask to preload the config from a module and then override the config from a file in the instance folder if it exists:
app= Flask(__name__, instance_relative_config= True) app.config.from_object('yourapplication.default_settings') app.config.from_pyfile('application.cfg', silent=True)
82 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
The path to the instance folder can be found via the Flask.instance_path. Flask also provides a shortcut to open a file from the instance folder with Flask.open_instance_resource(). Example usage for both:
filename= os.path.join(app.instance_path,'application.cfg') with open(filename) as f: config=f.read()
# or via open_instance_resource: with app.open_instance_resource('application.cfg') as f: config=f.read()
1.12 Signals
New in version 0.6. Starting with Flask 0.6, there is integrated support for signalling in Flask. This support is provided by the excellent blinker library and will gracefully fall back if it is not available. What are signals? Signals help you decouple applications by sending notifications when actions occur elsewhere in the core framework or another Flask extensions. In short, signals allow certain senders to notify subscribers that something happened. Flask comes with a couple of signals and other extensions might provide more. Also keep in mind that signals are intended to notify subscribers and should not encourage subscribers to modify data. You will notice that there are signals that appear to do the same thing like some of the builtin decorators do (eg: request_started is very similar to before_request()). However, there are differences in how they work. The core before_request() handler, for example, is executed in a specific order and is able to abort the request early by returning a response. In contrast all signal handlers are executed in undefined order and do not modify any data. The big advantage of signals over handlers is that you can safely subscribe to them for just a split second. These temporary subscriptions are helpful for unit testing for example. Say you want to know what templates were rendered as part of a request: signals allow you to do exactly that.
1.12.1 Subscribing to Signals
To subscribe to a signal, you can use the connect() method of a signal. The first argument is the function that should be called when the signal is emitted, the optional second argument specifies a sender. To unsubscribe from a signal, you can use the disconnect() method. For all core Flask signals, the sender is the application that issued the signal. When you subscribe to a signal, be sure to also provide a sender unless you really want to listen for signals from all applications. This is especially true if you are developing an extension. For example, here is a helper context manager that can be used in a unit test to determine which templates were rendered and what variables were passed to the template:
from flask import template_rendered from contextlib import contextmanager
@contextmanager def captured_templates(app): recorded=[] def record(sender, template, context, **extra): (continues on next page)
1.12. Signals 83 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) recorded.append((template, context)) template_rendered.connect(record, app) try: yield recorded finally: template_rendered.disconnect(record, app)
This can now easily be paired with a test client: with captured_templates(app) as templates: rv= app.test_client().get('/') assert rv.status_code == 200 assert len(templates) ==1 template, context= templates[0] assert template.name =='index.html' assert len(context['items']) == 10
Make sure to subscribe with an extra **extra argument so that your calls don’t fail if Flask introduces new arguments to the signals. All the template rendering in the code issued by the application app in the body of the with block will now be recorded in the templates variable. Whenever a template is rendered, the template object as well as context are appended to it. Additionally there is a convenient helper method (connected_to()) that allows you to temporarily subscribe a function to a signal with a context manager on its own. Because the return value of the context manager cannot be specified that way, you have to pass the list in as an argument: from flask import template_rendered def captured_templates(app, recorded, **extra): def record(sender, template, context): recorded.append((template, context)) return template_rendered.connected_to(record, app)
The example above would then look like this: templates=[] with captured_templates(app, templates, **extra): ... template, context= templates[0]
Blinker API Changes The connected_to() method arrived in Blinker with version 1.1.
1.12.2 Creating Signals
If you want to use signals in your own application, you can use the blinker library directly. The most common use case are named signals in a custom Namespace.. This is what is recommended most of the time: from blinker import Namespace my_signals= Namespace()
Now you can create new signals like this:
84 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
model_saved= my_signals.signal('model-saved')
The name for the signal here makes it unique and also simplifies debugging. You can access the name of the signal with the name attribute.
For Extension Developers If you are writing a Flask extension and you want to gracefully degrade for missing blinker installations, you can do so by using the flask.signals.Namespace class.
1.12.3 Sending Signals
If you want to emit a signal, you can do so by calling the send() method. It accepts a sender as first argument and optionally some keyword arguments that are forwarded to the signal subscribers: class Model(object): ...
def save(self): model_saved.send(self)
Try to always pick a good sender. If you have a class that is emitting a signal, pass self as sender. If you are emitting a signal from a random function, you can pass current_app._get_current_object() as sender.
Passing Proxies as Senders Never pass current_app as sender to a signal. Use current_app._get_current_object() instead. The reason for this is that current_app is a proxy and not the real application object.
1.12.4 Signals and Flask’s Request Context
Signals fully support The Request Context when receiving signals. Context-local variables are consistently available between request_started and request_finished, so you can rely on flask.g and others as needed. Note the limitations described in Sending Signals and the request_tearing_down signal.
1.12.5 Decorator Based Signal Subscriptions
With Blinker 1.1 you can also easily subscribe to signals by using the new connect_via() decorator: from flask import template_rendered
@template_rendered.connect_via(app) def when_template_rendered(sender, template, context, **extra): print'Template %s is rendered with %s'% (template.name, context)
1.12.6 Core Signals
Take a look at Signals for a list of all builtin signals.
1.12. Signals 85 Flask Documentation (1.1.x), Release 1.1.4
1.13 Pluggable Views
New in version 0.7. Flask 0.7 introduces pluggable views inspired by the generic views from Django which are based on classes instead of functions. The main intention is that you can replace parts of the implementations and this way have customizable pluggable views.
1.13.1 Basic Principle
Consider you have a function that loads a list of objects from the database and renders into a template:
@app.route('/users/') def show_users(page): users= User.query.all() return render_template('users.html', users=users)
This is simple and flexible, but if you want to provide this view in a generic fashion that can be adapted to other models and templates as well you might want more flexibility. This is where pluggable class-based views come into place. As the first step to convert this into a class based view you would do this: from flask.views import View class ShowUsers(View):
def dispatch_request(self): users= User.query.all() return render_template('users.html', objects=users) app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))
As you can see what you have to do is to create a subclass of flask.views.View and implement dispatch_request(). Then we have to convert that class into an actual view function by using the as_view() class method. The string you pass to that function is the name of the endpoint that view will then have. But this by itself is not helpful, so let’s refactor the code a bit: from flask.views import View class ListView(View):
def get_template_name(self): raise NotImplementedError()
def render_template(self, context): return render_template(self.get_template_name(), **context)
def dispatch_request(self): context={'objects': self.get_objects()} return self.render_template(context) class UserView(ListView):
def get_template_name(self): return 'users.html'
(continues on next page)
86 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def get_objects(self): return User.query.all()
This of course is not that helpful for such a small example, but it’s good enough to explain the basic principle. When you have a class-based view the question comes up what self points to. The way this works is that whenever the request is dispatched a new instance of the class is created and the dispatch_request() method is called with the parameters from the URL rule. The class itself is instantiated with the parameters passed to the as_view() function. For instance you can write a class like this:
class RenderTemplateView(View): def __init__(self, template_name): self.template_name= template_name def dispatch_request(self): return render_template(self.template_name)
And then you can register it like this:
app.add_url_rule('/about', view_func=RenderTemplateView.as_view( 'about_page', template_name='about.html'))
1.13.2 Method Hints
Pluggable views are attached to the application like a regular function by either using route() or better add_url_rule(). That however also means that you would have to provide the names of the HTTP methods the view supports when you attach this. In order to move that information to the class you can provide a methods attribute that has this information:
class MyView(View): methods=['GET','POST']
def dispatch_request(self): if request.method =='POST': ......
app.add_url_rule('/myview', view_func=MyView.as_view('myview'))
1.13.3 Method Based Dispatching
For RESTful APIs it’s especially helpful to execute a different function for each HTTP method. With the flask. views.MethodView you can easily do that. Each HTTP method maps to a function with the same name (just in lowercase):
from flask.views import MethodView
class UserAPI(MethodView):
def get(self): users= User.query.all() ...
def post(self): (continues on next page)
1.13. Pluggable Views 87 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) user= User.from_form_data(request.form) ... app.add_url_rule('/users/', view_func=UserAPI.as_view('users'))
That way you also don’t have to provide the methods attribute. It’s automatically set based on the methods defined in the class.
1.13.4 Decorating Views
Since the view class itself is not the view function that is added to the routing system it does not make much sense to decorate the class itself. Instead you either have to decorate the return value of as_view() by hand: def user_required(f): """Checks whether user is logged in or raises error 401.""" def decorator(*args, **kwargs): if not g.user: abort(401) return f(*args, **kwargs) return decorator view= user_required(UserAPI.as_view('users')) app.add_url_rule('/users/', view_func=view)
Starting with Flask 0.8 there is also an alternative way where you can specify a list of decorators to apply in the class declaration: class UserAPI(MethodView): decorators= [user_required]
Due to the implicit self from the caller’s perspective you cannot use regular view decorators on the individual methods of the view however, keep this in mind.
1.13.5 Method Views for APIs
Web APIs are often working very closely with HTTP verbs so it makes a lot of sense to implement such an API based on the MethodView. That said, you will notice that the API will require different URL rules that go to the same method view most of the time. For instance consider that you are exposing a user object on the web:
URL Method Description /users/ GET Gives a list of all users /users/ POST Creates a new user /users/
So how would you go about doing that with the MethodView? The trick is to take advantage of the fact that you can provide multiple rules to the same view. Let’s assume for the moment the view would look like this:
88 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
class UserAPI(MethodView):
def get(self, user_id): if user_id is None: # return a list of users pass else: # expose a single user pass
def post(self): # create a new user pass
def delete(self, user_id): # delete a single user pass
def put(self, user_id): # update a single user pass
So how do we hook this up with the routing system? By adding two rules and explicitly mentioning the methods for each: user_view= UserAPI.as_view('user_api') app.add_url_rule('/users/', defaults={'user_id': None}, view_func=user_view, methods=['GET',]) app.add_url_rule('/users/', view_func=user_view, methods=['POST',]) app.add_url_rule('/users/
If you have a lot of APIs that look similar you can refactor that registration code: def register_api(view, endpoint, url, pk='id', pk_type='int'): view_func= view.as_view(endpoint) app.add_url_rule(url, defaults={pk: None}, view_func=view_func, methods=['GET',]) app.add_url_rule(url, view_func=view_func, methods=['POST',]) app.add_url_rule('%s<%s:%s>'% (url, pk_type, pk), view_func=view_func, methods=['GET','PUT','DELETE']) register_api(UserAPI,'user_api','/users/', pk='user_id')
1.14 The Application Context
The application context keeps track of the application-level data during a request, CLI command, or other activity. Rather than passing the application around to each function, the current_app and g proxies are accessed instead. This is similar to the The Request Context, which keeps track of request-level data during a request. A corresponding application context is pushed when a request context is pushed.
1.14. The Application Context 89 Flask Documentation (1.1.x), Release 1.1.4
1.14.1 Purpose of the Context
The Flask application object has attributes, such as config, that are useful to access within views and CLI com- mands. However, importing the app instance within the modules in your project is prone to circular import issues. When using the app factory pattern or writing reusable blueprints or extensions there won’t be an app instance to import at all. Flask solves this issue with the application context. Rather than referring to an app directly, you use the current_app proxy, which points to the application handling the current activity. Flask automatically pushes an application context when handling a request. View functions, error handlers, and other functions that run during a request will have access to current_app. Flask will also automatically push an app context when running CLI commands registered with Flask.cli using @app.cli.command().
1.14.2 Lifetime of the Context
The application context is created and destroyed as necessary. When a Flask application begins handling a request, it pushes an application context and a request context. When the request ends it pops the request context then the application context. Typically, an application context will have the same lifetime as a request. See The Request Context for more information about how the contexts work and the full life cycle of a request.
1.14.3 Manually Push a Context
If you try to access current_app, or anything that uses it, outside an application context, you’ll get this error message:
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context().
If you see that error while configuring your application, such as when initializing an extension, you can push a context manually since you have direct access to the app. Use app_context() in a with block, and everything that runs in the block will have access to current_app.
def create_app(): app= Flask(__name__)
with app.app_context(): init_db()
return app
If you see that error somewhere else in your code not related to configuring the application, it most likely indicates that you should move that code into a view function or CLI command.
1.14.4 Storing Data
The application context is a good place to store common data during a request or CLI command. Flask provides the g object for this purpose. It is a simple namespace object that has the same lifetime as an application context.
90 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Note: The g name stands for “global”, but that is referring to the data being global within a context. The data on g is lost after the context ends, and it is not an appropriate place to store data between requests. Use the session or a database to store data across requests.
A common use for g is to manage resources during a request. 1. get_X() creates resource X if it does not exist, caching it as g.X. 2. teardown_X() closes or otherwise deallocates the resource if it exists. It is registered as a teardown_appcontext() handler. For example, you can manage a database connection using this pattern:
from flask import g
def get_db(): if 'db' not in g: g.db= connect_to_database()
return g.db
@app.teardown_appcontext def teardown_db(exception): db=g.pop('db', None)
if db is not None: db.close()
During a request, every call to get_db() will return the same connection, and it will be closed automatically at the end of the request. You can use LocalProxy to make a new context local from get_db():
from werkzeug.local import LocalProxy db= LocalProxy(get_db)
Accessing db will call get_db internally, in the same way that current_app works.
If you’re writing an extension, g should be reserved for user code. You may store internal data on the context itself, but be sure to use a sufficiently unique name. The current context is accessed with _app_ctx_stack.top. For more information see Flask Extension Development.
1.14.5 Events and Signals
The application will call functions registered with teardown_appcontext() when the application context is popped. If signals_available is true, the following signals are sent: appcontext_pushed, appcontext_tearing_down, and appcontext_popped.
1.15 The Request Context
The request context keeps track of the request-level data during a request. Rather than passing the request object to each function that runs during a request, the request and session proxies are accessed instead.
1.15. The Request Context 91 Flask Documentation (1.1.x), Release 1.1.4
This is similar to the The Application Context, which keeps track of the application-level data independent of a request. A corresponding application context is pushed when a request context is pushed.
1.15.1 Purpose of the Context
When the Flask application handles a request, it creates a Request object based on the environment it received from the WSGI server. Because a worker (thread, process, or coroutine depending on the server) handles only one request at a time, the request data can be considered global to that worker during that request. Flask uses the term context local for this. Flask automatically pushes a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the request proxy, which points to the request object for the current request.
1.15.2 Lifetime of the Context
When a Flask application begins handling a request, it pushes a request context, which also pushes an The Application Context. When the request ends it pops the request context then the application context. The context is unique to each thread (or other worker type). request cannot be passed to another thread, the other thread will have a different context stack and will not know about the request the parent thread was pointing to. Context locals are implemented in Werkzeug. See Context Locals for more information on how this works internally.
1.15.3 Manually Push a Context
If you try to access request, or anything that uses it, outside a request context, you’ll get this error message:
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.
This should typically only happen when testing code that expects an active request. One option is to use the test client to simulate a full request. Or you can use test_request_context() in a with block, and everything that runs in the block will have access to request, populated with your test data.
def generate_report(year): format= request.args.get('format') ...
with app.test_request_context( '/make_report/2017', data={'format':'short'}): generate_report()
If you see that error somewhere else in your code not related to testing, it most likely indicates that you should move that code into a view function. For information on how to use the request context from the interactive Python shell, see Working with the Shell.
92 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.15.4 How the Context Works
The Flask.wsgi_app() method is called to handle each request. It manages the contexts during the request. Internally, the request and application contexts work as stacks, _request_ctx_stack and _app_ctx_stack. When contexts are pushed onto the stack, the proxies that depend on them are available and point at information from the top context on the stack. When the request starts, a RequestContext is created and pushed, which creates and pushes an AppContext first if a context for that application is not already the top context. While these contexts are pushed, the current_app, g, request, and session proxies are available to the original thread handling the request. Because the contexts are stacks, other contexts may be pushed to change the proxies during a request. While this is not a common pattern, it can be used in advanced applications to, for example, do internal redirects or chain different applications together. After the request is dispatched and a response is generated and sent, the request context is popped, which then pops the application context. Immediately before they are popped, the teardown_request() and teardown_appcontext() functions are executed. These execute even if an unhandled exception occurred during dispatch.
1.15.5 Callbacks and Errors
Flask dispatches a request in multiple stages which can affect the request, response, and how errors are handled. The contexts are active during all of these stages. A Blueprint can add handlers for these events that are specific to the blueprint. The handlers for a blueprint will run if the blueprint owns the route that matches the request. 1. Before each request, before_request() functions are called. If one of these functions return a value, the other functions are skipped. The return value is treated as the response and the view function is not called. 2. If the before_request() functions did not return a response, the view function for the matched route is called and returns a response. 3. The return value of the view is converted into an actual response object and passed to the after_request() functions. Each function returns a modified or new response object. 4. After the response is returned, the contexts are popped, which calls the teardown_request() and teardown_appcontext() functions. These functions are called even if an unhandled exception was raised at any point above. If an exception is raised before the teardown functions, Flask tries to match it with an errorhandler() function to handle the exception and return a response. If no error handler is found, or the handler itself raises an exception, Flask returns a generic 500 Internal Server Error response. The teardown functions are still called, and are passed the exception object. If debug mode is enabled, unhandled exceptions are not converted to a 500 response and instead are propagated to the WSGI server. This allows the development server to present the interactive debugger with the traceback.
Teardown Callbacks
The teardown callbacks are independent of the request dispatch, and are instead called by the contexts when they are popped. The functions are called even if there is an unhandled exception during dispatch, and for manually pushed contexts. This means there is no guarantee that any other parts of the request dispatch have run first. Be sure to write these functions in a way that does not depend on other callbacks and will not fail. During testing, it can be useful to defer popping the contexts after the request ends, so that their data can be accessed in the test function. Use the test_client() as a with block to preserve the contexts until the with block exits.
1.15. The Request Context 93 Flask Documentation (1.1.x), Release 1.1.4
from flask import Flask, request
app= Flask(__name__)
@app.route('/') def hello(): print('during view') return 'Hello, World!'
@app.teardown_request def show_teardown(exception): print('after with block') with app.test_request_context(): print('during with block')
# teardown functions are called after the context with block exits with app.test_client() as client: client.get('/') # the contexts are not popped even though the request ended print(request.path)
# the contexts are popped and teardown functions are called after # the client with block exits
Signals
If signals_available is true, the following signals are sent: 1. request_started is sent before the before_request() functions are called. 2. request_finished is sent after the after_request() functions are called. 3. got_request_exception is sent when an exception begins to be handled, but before an errorhandler() is looked up or called. 4. request_tearing_down is sent after the teardown_request() functions are called.
1.15.6 Context Preservation on Error
At the end of a request, the request context is popped and all data associated with it is destroyed. If an error occurs during development, it is useful to delay destroying the data for debugging purposes. When the development server is running in development mode (the FLASK_ENV environment variable is set to 'development'), the error and data will be preserved and shown in the interactive debugger. This behavior can be controlled with the PRESERVE_CONTEXT_ON_EXCEPTION config. As described above, it defaults to True in the development environment. Do not enable PRESERVE_CONTEXT_ON_EXCEPTION in production, as it will cause your application to leak memory on exceptions.
94 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.15.7 Notes On Proxies
Some of the objects provided by Flask are proxies to other objects. The proxies are accessed in the same way for each worker thread, but point to the unique object bound to each worker behind the scenes as described on this page. Most of the time you don’t have to care about that, but there are some exceptions where it is good to know that this object is actually a proxy: • The proxy objects cannot fake their type as the actual object types. If you want to perform instance checks, you have to do that on the object being proxied. • The reference to the proxied object is needed in some situations, such as sending Signals or passing data to a background thread. If you need to access the underlying object that is proxied, use the _get_current_object() method:
app= current_app._get_current_object() my_signal.send(app)
1.16 Modular Applications with Blueprints
New in version 0.7. Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications. A Blueprint object works similarly to a Flask application object, but it is not actually an application. Rather it is a blueprint of how to construct or extend an application.
1.16.1 Why Blueprints?
Blueprints in Flask are intended for these cases: • Factor an application into a set of blueprints. This is ideal for larger applications; a project could instantiate an application object, initialize several extensions, and register a collection of blueprints. • Register a blueprint on an application at a URL prefix and/or subdomain. Parameters in the URL pre- fix/subdomain become common view arguments (with defaults) across all view functions in the blueprint. • Register a blueprint multiple times on an application with different URL rules. • Provide template filters, static files, templates, and other utilities through blueprints. A blueprint does not have to implement applications or view functions. • Register a blueprint on an application for any of these cases when initializing a Flask extension. A blueprint in Flask is not a pluggable app because it is not actually an application – it’s a set of operations which can be registered on an application, even multiple times. Why not have multiple application objects? You can do that (see Application Dispatching), but your applications will have separate configs and will be managed at the WSGI layer. Blueprints instead provide separation at the Flask level, share application config, and can change an application object as necessary with being registered. The downside is that you cannot unregister a blueprint once an application was created without having to destroy the whole application object.
1.16. Modular Applications with Blueprints 95 Flask Documentation (1.1.x), Release 1.1.4
1.16.2 The Concept of Blueprints
The basic concept of blueprints is that they record operations to execute when registered on an application. Flask as- sociates view functions with blueprints when dispatching requests and generating URLs from one endpoint to another.
1.16.3 My First Blueprint
This is what a very basic blueprint looks like. In this case we want to implement a blueprint that does simple rendering of static templates:
from flask import Blueprint, render_template, abort from jinja2 import TemplateNotFound
simple_page= Blueprint('simple_page', __name__, template_folder='templates')
@simple_page.route('/', defaults={'page':'index'}) @simple_page.route('/
When you bind a function with the help of the @simple_page.route decorator, the blueprint will record the intention of registering the function show on the application when it’s later registered. Additionally it will prefix the endpoint of the function with the name of the blueprint which was given to the Blueprint constructor (in this case also simple_page). The blueprint’s name does not modify the URL, only the endpoint.
1.16.4 Registering Blueprints
So how do you register that blueprint? Like this:
from flask import Flask from yourapplication.simple_page import simple_page app= Flask(__name__) app.register_blueprint(simple_page)
If you check the rules registered on the application, you will find these:
>>> app.url_map Map([
The first one is obviously from the application itself for the static files. The other two are for the show function of the simple_page blueprint. As you can see, they are also prefixed with the name of the blueprint and separated by a dot (.). Blueprints however can also be mounted at different locations:
app.register_blueprint(simple_page, url_prefix='/pages')
And sure enough, these are the generated rules:
96 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
>>> app.url_map Map([
On top of that you can register blueprints multiple times though not every blueprint might respond properly to that. In fact it depends on how the blueprint is implemented if it can be mounted more than once.
1.16.5 Blueprint Resources
Blueprints can provide resources as well. Sometimes you might want to introduce a blueprint only for the resources it provides.
Blueprint Resource Folder
Like for regular applications, blueprints are considered to be contained in a folder. While multiple blueprints can originate from the same folder, it does not have to be the case and it’s usually not recommended. The folder is inferred from the second argument to Blueprint which is usually __name__. This argument specifies what logical Python module or package corresponds to the blueprint. If it points to an actual Python package that package (which is a folder on the filesystem) is the resource folder. If it’s a module, the package the module is contained in will be the resource folder. You can access the Blueprint.root_path property to see what the resource folder is:
>>> simple_page.root_path '/Users/username/TestProject/yourapplication'
To quickly open sources from this folder you can use the open_resource() function:
with simple_page.open_resource('static/style.css') as f: code=f.read()
Static Files
A blueprint can expose a folder with static files by providing the path to the folder on the filesystem with the static_folder argument. It is either an absolute path or relative to the blueprint’s location:
admin= Blueprint('admin', __name__, static_folder='static')
By default the rightmost part of the path is where it is exposed on the web. This can be changed with the static_url_path argument. Because the folder is called static here it will be available at the url_prefix of the blueprint + /static. If the blueprint has the prefix /admin, the static URL will be /admin/static. The endpoint is named blueprint_name.static. You can generate URLs to it with url_for() like you would with the static folder of the application:
url_for('admin.static', filename='style.css')
However, if the blueprint does not have a url_prefix, it is not possible to access the blueprint’s static folder. This is because the URL would be /static in this case, and the application’s /static route takes precedence. Unlike template folders, blueprint static folders are not searched if the file does not exist in the application static folder.
1.16. Modular Applications with Blueprints 97 Flask Documentation (1.1.x), Release 1.1.4
Templates
If you want the blueprint to expose templates you can do that by providing the template_folder parameter to the Blueprint constructor:
admin= Blueprint('admin', __name__, template_folder='templates')
For static files, the path can be absolute or relative to the blueprint resource folder. The template folder is added to the search path of templates but with a lower priority than the actual application’s template folder. That way you can easily override templates that a blueprint provides in the actual application. This also means that if you don’t want a blueprint template to be accidentally overridden, make sure that no other blueprint or actual application template has the same relative path. When multiple blueprints provide the same relative template path the first blueprint registered takes precedence over the others. So if you have a blueprint in the folder yourapplication/admin and you want to render the template 'admin/ index.html' and you have provided templates as a template_folder you will have to create a file like this: yourapplication/admin/templates/admin/index.html. The reason for the extra admin folder is to avoid getting our template overridden by a template named index.html in the actual application template folder. To further reiterate this: if you have a blueprint named admin and you want to render a template called index.html which is specific to this blueprint, the best idea is to lay out your templates like this:
yourpackage/ blueprints/ admin/ templates/ admin/ index.html __init__.py
And then when you want to render the template, use admin/index.html as the name to look up the template by. If you encounter problems loading the correct templates enable the EXPLAIN_TEMPLATE_LOADING config variable which will instruct Flask to print out the steps it goes through to locate templates on every render_template call.
1.16.6 Building URLs
If you want to link from one page to another you can use the url_for() function just like you normally would do just that you prefix the URL endpoint with the name of the blueprint and a dot (.):
url_for('admin.index')
Additionally if you are in a view function of a blueprint or a rendered template and you want to link to another endpoint of the same blueprint, you can use relative redirects by prefixing the endpoint with a dot only:
url_for('.index')
This will link to admin.index for instance in case the current request was dispatched to any other admin blueprint endpoint.
1.16.7 Error Handlers
Blueprints support the errorhandler decorator just like the Flask application object, so it is easy to make Blueprint-specific custom error pages. Here is an example for a “404 Page Not Found” exception:
98 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
@simple_page.errorhandler(404) def page_not_found(e): return render_template('pages/404.html')
Most errorhandlers will simply work as expected; however, there is a caveat concerning handlers for 404 and 405 exceptions. These errorhandlers are only invoked from an appropriate raise statement or a call to abort in another of the blueprint’s view functions; they are not invoked by, e.g., an invalid URL access. This is because the blueprint does not “own” a certain URL space, so the application instance has no way of knowing which blueprint error handler it should run if given an invalid URL. If you would like to execute different handling strategies for these errors based on URL prefixes, they may be defined at the application level using the request proxy object:
@app.errorhandler(404) @app.errorhandler(405) def _handle_api_error(ex): if request.path.startswith('/api/'): return jsonify_error(ex) else: return ex
More information on error handling see Custom Error Pages.
1.17 Extensions
Extensions are extra packages that add functionality to a Flask application. For example, an extension might add support for sending email or connecting to a database. Some extensions add entire new frameworks to help build certain types of applications, like a REST API.
1.17.1 Finding Extensions
Flask extensions are usually named “Flask-Foo” or “Foo-Flask”. You can search PyPI for packages tagged with Framework :: Flask.
1.17.2 Using Extensions
Consult each extension’s documentation for installation, configuration, and usage instructions. Generally, extensions pull their own configuration from app.config and are passed an application instance during initialization. For example, an extension called “Flask-Foo” might be used like this: from flask_foo import Foo foo= Foo() app= Flask(__name__) app.config.update( FOO_BAR='baz', FOO_SPAM='eggs', ) foo.init_app(app)
1.17. Extensions 99 Flask Documentation (1.1.x), Release 1.1.4
1.17.3 Building Extensions
While the PyPI contains many Flask extensions, you may not find an extension that fits your need. If this is the case, you can create your own. Read Flask Extension Development to develop your own Flask extension.
1.18 Command Line Interface
Installing Flask installs the flask script, a Click command line interface, in your virtualenv. Executed from the terminal, this script gives access to built-in, extension, and application-defined commands. The --help option will give more information about any commands and options.
1.18.1 Application Discovery
The flask command is installed by Flask, not your application; it must be told where to find your application in order to use it. The FLASK_APP environment variable is used to specify how to load the application. Unix Bash (Linux, Mac, etc.):
$ export FLASK_APP=hello $ flask run
Windows CMD:
> set FLASK_APP=hello > flask run
Windows PowerShell:
> $env:FLASK_APP = "hello" > flask run
While FLASK_APP supports a variety of options for specifying your application, most use cases should be simple. Here are the typical values: (nothing) The file wsgi.py is imported, automatically detecting an app (app). This provides an easy way to create an app from a factory with extra arguments. FLASK_APP=hello The name is imported, automatically detecting an app (app) or factory (create_app).
FLASK_APP has three parts: an optional path that sets the current working directory, a Python file or dotted import path, and an optional variable name of the instance or factory. If the name is a factory, it can optionally be followed by arguments in parentheses. The following values demonstrate these parts: FLASK_APP=src/hello Sets the current working directory to src then imports hello. FLASK_APP=hello.web Imports the path hello.web. FLASK_APP=hello:app2 Uses the app2 Flask instance in hello. FLASK_APP="hello:create_app('dev')" The create_app factory in hello is called with the string 'dev' as the argument. If FLASK_APP is not set, the command will try to import “app” or “wsgi” (as a “.py” file, or package) and try to detect an application instance or factory.
100 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Within the given import, the command looks for an application instance named app or application, then any application instance. If no instance is found, the command looks for a factory function named create_app or make_app that returns an instance. When calling an application factory, if the factory takes an argument named script_info, then the ScriptInfo instance is passed as a keyword argument. If the application factory takes only one argument and no parentheses follow the factory name, the ScriptInfo instance is passed as a positional argument. If parentheses follow the factory name, their contents are parsed as Python literals and passes as arguments to the function. This means that strings must still be in quotes.
1.18.2 Run the Development Server
The run command will start the development server. It replaces the Flask.run() method in most cases.
$ flask run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Warning: Do not use this command to run your application in production. Only use the development server during development. The development server is provided for convenience, but is not designed to be particularly secure, stable, or efficient. See Deployment Options for how to run in production.
1.18.3 Open a Shell
To explore the data in your application, you can start an interactive Python shell with the shell command. An application context will be active, and the app instance will be imported.
$ flask shell Python 3.6.2 (default, Jul 20 2017, 03:52:27) [GCC 7.1.1 20170630] on linux App: example Instance: /home/user/Projects/hello/instance >>>
Use shell_context_processor() to add other automatic imports.
1.18.4 Environments
New in version 1.0. The environment in which the Flask app runs is set by the FLASK_ENV environment variable. If not set it defaults to production. The other recognized environment is development. Flask and extensions may choose to enable behaviors based on the environment. If the env is set to development, the flask command will enable debug mode and flask run will enable the interactive debugger and reloader.
$ FLASK_ENV=development flask run * Serving Flask app "hello" * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) (continues on next page)
1.18. Command Line Interface 101 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) * Restarting with inotify reloader * Debugger is active! * Debugger PIN: 223-456-919
Watch Extra Files with the Reloader
When using development mode, the reloader will trigger whenever your Python code or imported modules change. The reloader can watch additional files with the --extra-files option, or the FLASK_RUN_EXTRA_FILES environment variable. Multiple paths are separated with :, or ; on Windows.
$ flask run --extra-files file1:dirA/file2:dirB/ # or $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/ $ flask run * Running on http://127.0.0.1:8000/ * Detected change in '/path/to/file1', reloading
1.18.5 Debug Mode
Debug mode will be enabled when FLASK_ENV is development, as described above. If you want to control debug mode separately, use FLASK_DEBUG. The value 1 enables it, 0 disables it.
1.18.6 Environment Variables From dotenv
Rather than setting FLASK_APP each time you open a new terminal, you can use Flask’s dotenv support to set environment variables automatically. If python-dotenv is installed, running the flask command will set environment variables defined in the files .env and .flaskenv. This can be used to avoid having to set FLASK_APP manually every time you open a new terminal, and to set configuration using environment variables similar to how some deployment services work. Variables set on the command line are used over those set in .env, which are used over those set in .flaskenv. .flaskenv should be used for public variables, such as FLASK_APP, while .env should not be committed to your repository so that it can set private variables. Directories are scanned upwards from the directory you call flask from to locate the files. The current working directory will be set to the location of the file, with the assumption that that is the top level project directory. The files are only loaded by the flask command or calling run(). If you would like to load these files when running in production, you should call load_dotenv() manually.
Setting Command Options
Click is configured to load default values for command options from environment variables. The variables use the pattern FLASK_COMMAND_OPTION. For example, to set the port for the run command, instead of flask run --port 8000:
$ export FLASK_RUN_PORT=8000 $ flask run * Running on http://127.0.0.1:8000/
These can be added to the .flaskenv file just like FLASK_APP to control default command options.
102 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Disable dotenv
The flask command will show a message if it detects dotenv files but python-dotenv is not installed.
$ flask run * Tip: There are .env files present. Do "pip install python-dotenv" to use them.
You can tell Flask not to load dotenv files even when python-dotenv is installed by setting the FLASK_SKIP_DOTENV environment variable. This can be useful if you want to load them manually, or if you’re using a project runner that loads them already. Keep in mind that the environment variables must be set before the app loads or it won’t configure as expected.
$ export FLASK_SKIP_DOTENV=1 $ flask run
1.18.7 Environment Variables From virtualenv
If you do not want to install dotenv support, you can still set environment variables by adding them to the end of the virtualenv’s activate script. Activating the virtualenv will set the variables. Unix Bash, venv/bin/activate:
$ export FLASK_APP=hello
Windows CMD, venv\Scripts\activate.bat:
> set FLASK_APP=hello
It is preferred to use dotenv support over this, since .flaskenv can be committed to the repository so that it works automatically wherever the project is checked out.
1.18.8 Custom Commands
The flask command is implemented using Click. See that project’s documentation for full information about writing commands. This example adds the command create-user that takes the argument name.
import click from flask import Flask
app= Flask(__name__)
@app.cli.command("create-user") @click.argument("name") def create_user(name): ...
$ flask create-user admin
This example adds the same command, but as user create, a command in a group. This is useful if you want to organize multiple related commands.
1.18. Command Line Interface 103 Flask Documentation (1.1.x), Release 1.1.4
import click from flask import Flask from flask.cli import AppGroup
app= Flask(__name__) user_cli= AppGroup('user')
@user_cli.command('create') @click.argument('name') def create_user(name): ...
app.cli.add_command(user_cli)
$ flask user create demo
See Testing CLI Commands for an overview of how to test your custom commands.
Registering Commands with Blueprints
If your application uses blueprints, you can optionally register CLI commands directly onto them. When your blueprint is registered onto your application, the associated commands will be available to the flask command. By default, those commands will be nested in a group matching the name of the blueprint.
from flask import Blueprint
bp= Blueprint('students', __name__)
@bp.cli.command('create') @click.argument('name') def create(name): ...
app.register_blueprint(bp)
$ flask students create alice
You can alter the group name by specifying the cli_group parameter when creating the Blueprint object, or later with app.register_blueprint(bp, cli_group='...'). The following are equivalent:
bp= Blueprint('students', __name__, cli_group='other') # or app.register_blueprint(bp, cli_group='other')
$ flask other create alice
Specifying cli_group=None will remove the nesting and merge the commands directly to the application’s level:
bp= Blueprint('students', __name__, cli_group= None) # or app.register_blueprint(bp, cli_group=None)
$ flask create alice
104 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Application Context
Commands added using the Flask app’s cli command() decorator will be executed with an application context pushed, so your command and extensions have access to the app and its configuration. If you create a command using the Click command() decorator instead of the Flask decorator, you can use with_appcontext() to get the same behavior.
import click from flask.cli import with_appcontext
@click.command() @with_appcontext def do_work(): ...
app.cli.add_command(do_work)
If you’re sure a command doesn’t need the context, you can disable it:
@app.cli.command(with_appcontext=False) def do_work(): ...
1.18.9 Plugins
Flask will automatically load commands specified in the flask.commands entry point. This is useful for extensions that want to add commands when they are installed. Entry points are specified in setup.py
from setuptools import setup
setup( name='flask-my-extension', ..., entry_points={ 'flask.commands':[ 'my-command=flask_my_extension.commands:cli' ], }, )
Inside flask_my_extension/commands.py you can then export a Click object:
import click
@click.command() def cli(): ...
Once that package is installed in the same virtualenv as your Flask project, you can run flask my-command to invoke the command.
1.18.10 Custom Scripts
When you are using the app factory pattern, it may be more convenient to define your own Click script. Instead of using FLASK_APP and letting Flask load your application, you can create your own Click object and export it as a
1.18. Command Line Interface 105 Flask Documentation (1.1.x), Release 1.1.4
console script entry point. Create an instance of FlaskGroup and pass it the factory:
import click from flask import Flask from flask.cli import FlaskGroup
def create_app(): app= Flask('wiki') # other setup return app
@click.group(cls=FlaskGroup, create_app=create_app) def cli(): """Management script for the Wiki application."""
Define the entry point in setup.py:
from setuptools import setup
setup( name='flask-my-extension', ..., entry_points={ 'console_scripts':[ 'wiki=wiki:cli' ], }, )
Install the application in the virtualenv in editable mode and the custom script is available. Note that you don’t need to set FLASK_APP.
$ pip install -e . $ wiki run
Errors in Custom Scripts When using a custom script, if you introduce an error in your module-level code, the reloader will fail because it can no longer load the entry point. The flask command, being separate from your code, does not have this issue and is recommended in most cases.
1.18.11 PyCharm Integration
PyCharm Professional provides a special Flask run configuration. For the Community Edition, we need to configure it to call the flask run CLI command with the correct environment variables. These instructions should be similar for any other IDE you might want to use. In PyCharm, with your project open, click on Run from the menu bar and go to Edit Configurations. You’ll be greeted by a screen similar to this:
106 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
There’s quite a few options to change, but once we’ve done it for one command, we can easily copy the entire config- uration and make a single tweak to give us access to other commands, including any custom ones you may implement yourself. Click the + (Add New Configuration) button and select Python. Give the configuration a name such as “flask run”. For the flask run command, check “Single instance only” since you can’t run the server more than once at the same time. Select Module name from the dropdown (A) then input flask. The Parameters field (B) is set to the CLI command to execute (with any arguments). In this example we use run, which will run the development server. You can skip this next step if you’re using Environment Variables From dotenv. We need to add an environment variable (C) to identify our application. Click on the browse button and add an entry with FLASK_APP on the left and the Python import or file on the right (hello for example). Add an entry with FLASK_ENV and set it to development. Next we need to set the working directory (D) to be the folder where our application resides. If you have installed your project as a package in your virtualenv, you may untick the PYTHONPATH options (E). This will more accurately match how you deploy the app later. Click Apply to save the configuration, or OK to save and close the window. Select the configuration in the main PyCharm window and click the play button next to it to run the server. Now that we have a configuration which runs flask run from within PyCharm, we can copy that configuration and alter the Script argument to run a different CLI command, e.g. flask shell.
1.18. Command Line Interface 107 Flask Documentation (1.1.x), Release 1.1.4
1.19 Development Server
Starting with Flask 0.11 there are multiple built-in ways to run a development server. The best one is the flask command line utility but you can also continue using the Flask.run() method.
1.19.1 Command Line
The flask command line script (Command Line Interface) is strongly recommended for development because it provides a superior reload experience due to how it loads the application. The basic usage is like this:
$ export FLASK_APP=my_application $ export FLASK_ENV=development $ flask run
This enables the development environment, including the interactive debugger and reloader, and then starts the server on http://localhost:5000/. The individual features of the server can be controlled by passing more arguments to the run option. For instance the reloader can be disabled:
$ flask run --no-reload
Note: Prior to Flask 1.0 the FLASK_ENV environment variable was not supported and you needed to enable debug mode by exporting FLASK_DEBUG=1. This can still be used to control debug mode, but you should prefer setting the development environment as shown above.
1.19.2 In Code
The alternative way to start the application is through the Flask.run() method. This will immediately launch a local server exactly the same way the flask script does. Example:
if __name__ =='__main__': app.run()
This works well for the common case but it does not work well for development which is why from Flask 0.11 onwards the flask method is recommended. The reason for this is that due to how the reload mechanism works there are some bizarre side-effects (like executing certain code twice, sometimes crashing without message or dying when a syntax or import error happens). It is however still a perfectly valid method for invoking a non automatic reloading application.
1.20 Working with the Shell
New in version 0.3. One of the reasons everybody loves Python is the interactive shell. It basically allows you to execute Python commands in real time and immediately get results back. Flask itself does not come with an interactive shell, because it does not require any specific setup upfront, just import your application and start playing around.
108 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
There are however some handy helpers to make playing around in the shell a more pleasant experience. The main issue with interactive console sessions is that you’re not triggering a request like a browser does which means that g, request and others are not available. But the code you want to test might depend on them, so what can you do? This is where some helper functions come in handy. Keep in mind however that these functions are not only there for interactive shell usage, but also for unit testing and other situations that require a faked request context. Generally it’s recommended that you read the The Request Context chapter of the documentation first.
1.20.1 Command Line Interface
Starting with Flask 0.11 the recommended way to work with the shell is the flask shell command which does a lot of this automatically for you. For instance the shell is automatically initialized with a loaded application context. For more information see Command Line Interface.
1.20.2 Creating a Request Context
The easiest way to create a proper request context from the shell is by using the test_request_context method which creates us a RequestContext:
>>> ctx= app.test_request_context()
Normally you would use the with statement to make this request object active, but in the shell it’s easier to use the push() and pop() methods by hand:
>>> ctx.push()
From that point onwards you can work with the request object until you call pop:
>>> ctx.pop()
1.20.3 Firing Before/After Request
By just creating a request context, you still don’t have run the code that is normally run before a request. This might result in your database being unavailable if you are connecting to the database in a before-request callback or the current user not being stored on the g object etc. This however can easily be done yourself. Just call preprocess_request():
>>> ctx= app.test_request_context() >>> ctx.push() >>> app.preprocess_request()
Keep in mind that the preprocess_request() function might return a response object, in that case just ignore it. To shutdown a request, you need to trick a bit before the after request functions (triggered by process_response()) operate on a response object:
>>> app.process_response(app.response_class())
1.20. Working with the Shell 109 Flask Documentation (1.1.x), Release 1.1.4
The functions registered as teardown_request() are automatically called when the context is popped. So this is the perfect place to automatically tear down resources that were needed by the request context (such as database connections).
1.20.4 Further Improving the Shell Experience
If you like the idea of experimenting in a shell, create yourself a module with stuff you want to star import into your interactive session. There you could also define some more helper methods for common things such as initializing the database, dropping tables etc. Just put them into a module (like shelltools) and import from there:
>>> from shelltools import *
1.21 Patterns for Flask
Certain features and interactions are common enough that you will find them in most web applications. For example, many applications use a relational database and user authentication. They will open a database connection at the beginning of the request and get the information for the logged in user. At the end of the request, the database connection is closed. These types of patterns may be a bit outside the scope of Flask itself, but Flask makes it easy to implement them. Some common patterns are collected in the following pages.
1.21.1 Larger Applications
Imagine a simple flask application structure that looks like this:
/yourapplication yourapplication.py /static style.css /templates layout.html index.html login.html ...
While this is fine for small applications, for larger applications it’s a good idea to use a package instead of a module. The tutorial is structured to use the package pattern, see the example code.
Simple Packages
To convert that into a larger one, just create a new folder yourapplication inside the existing one and move everything below it. Then rename yourapplication.py to __init__.py. (Make sure to delete all .pyc files first, otherwise things would most likely break) You should then end up with something like that:
110 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
/yourapplication /yourapplication __init__.py /static style.css /templates layout.html index.html login.html ...
But how do you run your application now? The naive python yourapplication/__init__.py will not work. Let’s just say that Python does not want modules in packages to be the startup file. But that is not a big problem, just add a new file called setup.py next to the inner yourapplication folder with the following contents:
from setuptools import setup
setup( name='yourapplication', packages=['yourapplication'], include_package_data=True, install_requires=[ 'flask', ], )
In order to run the application you need to export an environment variable that tells Flask where to find the application instance:
$ export FLASK_APP=yourapplication
If you are outside of the project directory make sure to provide the exact path to your application directory. Similarly you can turn on the development features like this:
$ export FLASK_ENV=development
In order to install and run the application you need to issue the following commands:
$ pip install -e . $ flask run
What did we gain from this? Now we can restructure the application a bit into multiple modules. The only thing you have to remember is the following quick checklist: 1. the Flask application object creation has to be in the __init__.py file. That way each module can import it safely and the __name__ variable will resolve to the correct package. 2. all the view functions (the ones with a route() decorator on top) have to be imported in the __init__.py file. Not the object itself, but the module it is in. Import the view module after the application object is created. Here’s an example __init__.py:
from flask import Flask app= Flask(__name__)
import yourapplication.views
1.21. Patterns for Flask 111 Flask Documentation (1.1.x), Release 1.1.4
And this is what views.py would look like:
from yourapplication import app
@app.route('/') def index(): return 'Hello World!'
You should then end up with something like that:
/yourapplication setup.py /yourapplication __init__.py views.py /static style.css /templates layout.html index.html login.html ...
Circular Imports Every Python programmer hates them, and yet we just added some: circular imports (That’s when two modules depend on each other. In this case views.py depends on __init__.py). Be advised that this is a bad idea in general but here it is actually fine. The reason for this is that we are not actually using the views in __init__.py and just ensuring the module is imported and we are doing that at the bottom of the file. There are still some problems with that approach but if you want to use decorators there is no way around that. Check out the Becoming Big section for some inspiration how to deal with that.
Working with Blueprints
If you have larger applications it’s recommended to divide them into smaller groups where each group is implemented with the help of a blueprint. For a gentle introduction into this topic refer to the Modular Applications with Blueprints chapter of the documentation.
1.21.2 Application Factories
If you are already using packages and blueprints for your application (Modular Applications with Blueprints) there are a couple of really nice ways to further improve the experience. A common pattern is creating the application object when the blueprint is imported. But if you move the creation of this object into a function, you can then create multiple instances of this app later. So why would you want to do this? 1. Testing. You can have instances of the application with different settings to test every case. 2. Multiple instances. Imagine you want to run different versions of the same application. Of course you could have multiple instances with different configs set up in your webserver, but if you use factories, you can have multiple instances of the same application running in the same application process which can be handy. So how would you then actually implement that?
112 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Basic Factories
The idea is to set up the application in a function. Like this: def create_app(config_filename): app= Flask(__name__) app.config.from_pyfile(config_filename)
from yourapplication.model import db db.init_app(app)
from yourapplication.views.admin import admin from yourapplication.views.frontend import frontend app.register_blueprint(admin) app.register_blueprint(frontend)
return app
The downside is that you cannot use the application object in the blueprints at import time. You can however use it from within a request. How do you get access to the application with the config? Use current_app: from flask import current_app, Blueprint, render_template admin= Blueprint('admin', __name__, url_prefix='/admin')
@admin.route('/') def index(): return render_template(current_app.config['INDEX_TEMPLATE'])
Here we look up the name of a template in the config.
Factories & Extensions
It’s preferable to create your extensions and app factories so that the extension object does not initially get bound to the application. Using Flask-SQLAlchemy, as an example, you should not do something along those lines: def create_app(config_filename): app= Flask(__name__) app.config.from_pyfile(config_filename)
db= SQLAlchemy(app)
But, rather, in model.py (or equivalent): db= SQLAlchemy() and in your application.py (or equivalent): def create_app(config_filename): app= Flask(__name__) app.config.from_pyfile(config_filename)
from yourapplication.model import db db.init_app(app)
Using this design pattern, no application-specific state is stored on the extension object, so one extension object can be used for multiple apps. For more information about the design of extensions refer to Flask Extension Development.
1.21. Patterns for Flask 113 Flask Documentation (1.1.x), Release 1.1.4
Using Applications
To run such an application, you can use the flask command:
$ export FLASK_APP=myapp $ flask run
Flask will automatically detect the factory (create_app or make_app) in myapp. You can also pass arguments to the factory like this:
$ export FLASK_APP="myapp:create_app('dev')" $ flask run
Then the create_app factory in myapp is called with the string 'dev' as the argument. See Command Line Interface for more detail.
Factory Improvements
The factory function above is not very clever, but you can improve it. The following changes are straightforward to implement: 1. Make it possible to pass in configuration values for unit tests so that you don’t have to create config files on the filesystem. 2. Call a function from a blueprint when the application is setting up so that you have a place to modify attributes of the application (like hooking in before/after request handlers etc.) 3. Add in WSGI middlewares when the application is being created if necessary.
1.21.3 Application Dispatching
Application dispatching is the process of combining multiple Flask applications on the WSGI level. You can combine not only Flask applications but any WSGI application. This would allow you to run a Django and a Flask application in the same interpreter side by side if you want. The usefulness of this depends on how the applications work internally. The fundamental difference from the module approach is that in this case you are running the same or different Flask applications that are entirely isolated from each other. They run different configurations and are dispatched on the WSGI level.
Working with this Document
Each of the techniques and examples below results in an application object that can be run with any WSGI server. For production, see Deployment Options. For development, Werkzeug provides a builtin server for development available at werkzeug.serving.run_simple():
from werkzeug.serving import run_simple run_simple('localhost', 5000, application, use_reloader=True)
Note that run_simple is not intended for use in production. Use a full-blown WSGI server. In order to use the interactive debugger, debugging must be enabled both on the application and the simple server. Here is the “hello world” example with debugging and run_simple:
114 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
from flask import Flask from werkzeug.serving import run_simple
app= Flask(__name__) app.debug= True
@app.route('/') def hello_world(): return 'Hello World!' if __name__ =='__main__': run_simple('localhost', 5000, app, use_reloader=True, use_debugger=True, use_evalex=True)
Combining Applications
If you have entirely separated applications and you want them to work next to each other in the same Python interpreter process you can take advantage of the werkzeug.wsgi.DispatcherMiddleware. The idea here is that each Flask application is a valid WSGI application and they are combined by the dispatcher middleware into a larger one that is dispatched based on prefix. For example you could have your main application run on / and your backend interface on /backend:
from werkzeug.middleware.dispatcher import DispatcherMiddleware from frontend_app import application as frontend from backend_app import application as backend
application= DispatcherMiddleware(frontend, { '/backend': backend })
Dispatch by Subdomain
Sometimes you might want to use multiple instances of the same application with different configurations. Assuming the application is created inside a function and you can call that function to instantiate it, that is really easy to imple- ment. In order to develop your application to support creating new instances in functions have a look at the Application Factories pattern. A very common example would be creating applications per subdomain. For instance you configure your webserver to dispatch all requests for all subdomains to your application and you then use the subdomain information to create user-specific instances. Once you have your server set up to listen on all subdomains you can use a very simple WSGI application to do the dynamic application creation. The perfect level for abstraction in that regard is the WSGI layer. You write your own WSGI application that looks at the request that comes and delegates it to your Flask application. If that application does not exist yet, it is dynamically created and remembered:
from threading import Lock
class SubdomainDispatcher(object):
def __init__(self, domain, create_app): self.domain= domain self.create_app= create_app (continues on next page)
1.21. Patterns for Flask 115 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) self.lock= Lock() self.instances={}
def get_application(self, host): host= host.split(':')[0] assert host.endswith(self.domain),'Configuration error' subdomain= host[:-len(self.domain)].rstrip('.') with self.lock: app= self.instances.get(subdomain) if app is None: app= self.create_app(subdomain) self.instances[subdomain]= app return app
def __call__(self, environ, start_response): app= self.get_application(environ['HTTP_HOST']) return app(environ, start_response)
This dispatcher can then be used like this: from myapplication import create_app, get_user_for_subdomain from werkzeug.exceptions import NotFound def make_app(subdomain): user= get_user_for_subdomain(subdomain) if user is None: # if there is no user for that subdomain we still have # to return a WSGI application that handles that request. # We can then just return the NotFound() exception as # application which will render a default 404 page. # You might also redirect the user to the main page then return NotFound()
# otherwise create the application for the specific user return create_app(user) application= SubdomainDispatcher('example.com', make_app)
Dispatch by Path
Dispatching by a path on the URL is very similar. Instead of looking at the Host header to figure out the subdomain one simply looks at the request path up to the first slash: from threading import Lock from werkzeug.wsgi import pop_path_info, peek_path_info class PathDispatcher(object):
def __init__(self, default_app, create_app): self.default_app= default_app self.create_app= create_app self.lock= Lock() self.instances={}
def get_application(self, prefix): (continues on next page)
116 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) with self.lock: app= self.instances.get(prefix) if app is None: app= self.create_app(prefix) if app is not None: self.instances[prefix]= app return app
def __call__(self, environ, start_response): app= self.get_application(peek_path_info(environ)) if app is not None: pop_path_info(environ) else: app= self.default_app return app(environ, start_response)
The big difference between this and the subdomain one is that this one falls back to another application if the creator function returns None: from myapplication import create_app, default_app, get_user_for_prefix def make_app(prefix): user= get_user_for_prefix(prefix) if user is not None: return create_app(user) application= PathDispatcher(default_app, make_app)
1.21.4 Implementing API Exceptions
It’s very common to implement RESTful APIs on top of Flask. One of the first things that developers run into is the realization that the builtin exceptions are not expressive enough for APIs and that the content type of text/html they are emitting is not very useful for API consumers. The better solution than using abort to signal errors for invalid API usage is to implement your own exception type and install an error handler for it that produces the errors in the format the user is expecting.
Simple Exception Class
The basic idea is to introduce a new exception that can take a proper human readable message, a status code for the error and some optional payload to give more context for the error. This is a simple example: from flask import jsonify class InvalidUsage(Exception): status_code= 400
def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message= message if status_code is not None: self.status_code= status_code (continues on next page)
1.21. Patterns for Flask 117 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) self.payload= payload
def to_dict(self): rv= dict(self.payload or ()) rv['message']= self.message return rv
A view can now raise that exception with an error message. Additionally some extra payload can be provided as a dictionary through the payload parameter.
Registering an Error Handler
At that point views can raise that error, but it would immediately result in an internal server error. The reason for this is that there is no handler registered for this error class. That however is easy to add:
@app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response= jsonify(error.to_dict()) response.status_code= error.status_code return response
Usage in Views
Here is how a view can use that functionality:
@app.route('/foo') def get_foo(): raise InvalidUsage('This view is gone', status_code=410)
1.21.5 Using URL Processors
New in version 0.7. Flask 0.7 introduces the concept of URL processors. The idea is that you might have a bunch of resources with common parts in the URL that you don’t always explicitly want to provide. For instance you might have a bunch of URLs that have the language code in it but you don’t want to have to handle it in every single function yourself. URL processors are especially helpful when combined with blueprints. We will handle both application specific URL processors here as well as blueprint specifics.
Internationalized Application URLs
Consider an application like this:
from flask import Flask, g
app= Flask(__name__)
@app.route('/
118 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) ...
@app.route('/
This is an awful lot of repetition as you have to handle the language code setting on the g object yourself in every single function. Sure, a decorator could be used to simplify this, but if you want to generate URLs from one function to another you would have to still provide the language code explicitly which can be annoying. For the latter, this is where url_defaults() functions come in. They can automatically inject values into a call to url_for(). The code below checks if the language code is not yet in the dictionary of URL values and if the endpoint wants a value named 'lang_code':
@app.url_defaults def add_language_code(endpoint, values): if 'lang_code' in values or not g.lang_code: return if app.url_map.is_endpoint_expecting(endpoint,'lang_code'): values['lang_code']=g.lang_code
The method is_endpoint_expecting() of the URL map can be used to figure out if it would make sense to provide a language code for the given endpoint. The reverse of that function are url_value_preprocessor()s. They are executed right after the request was matched and can execute code based on the URL values. The idea is that they pull information out of the values dictionary and put it somewhere else:
@app.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code= values.pop('lang_code', None)
That way you no longer have to do the lang_code assignment to g in every function. You can further improve that by writing your own decorator that prefixes URLs with the language code, but the more beautiful solution is using a blueprint. Once the 'lang_code' is popped from the values dictionary and it will no longer be forwarded to the view function reducing the code to this:
from flask import Flask, g
app= Flask(__name__)
@app.url_defaults def add_language_code(endpoint, values): if 'lang_code' in values or not g.lang_code: return if app.url_map.is_endpoint_expecting(endpoint,'lang_code'): values['lang_code']=g.lang_code
@app.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code= values.pop('lang_code', None)
@app.route('/
1.21. Patterns for Flask 119 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page)
@app.route('/
Internationalized Blueprint URLs
Because blueprints can automatically prefix all URLs with a common string it’s easy to automatically do that for every function. Furthermore blueprints can have per-blueprint URL processors which removes a whole lot of logic from the url_defaults() function because it no longer has to check if the URL is really interested in a 'lang_code' parameter:
from flask import Blueprint, g
bp= Blueprint('frontend', __name__, url_prefix='/
@bp.url_defaults def add_language_code(endpoint, values): values.setdefault('lang_code', g.lang_code)
@bp.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code= values.pop('lang_code')
@bp.route('/') def index(): ...
@bp.route('/about') def about(): ...
1.21.6 Deploying with Setuptools
Setuptools, is an extension library that is commonly used to distribute Python libraries and extensions. It extends distutils, a basic module installation system shipped with Python to also support various more complex constructs that make larger applications easier to distribute: • support for dependencies: a library or application can declare a list of other libraries it depends on which will be installed automatically for you. • package registry: setuptools registers your package with your Python installation. This makes it possible to query information provided by one package from another package. The best known feature of this system is the entry point support which allows one package to declare an “entry point” that another package can hook into to extend the other package. • installation manager: pip can install other libraries for you. If you have Python 2 (>=2.7.9) or Python 3 (>=3.4) installed from python.org, you will already have pip and setuptools on your system. Otherwise, you will need to install them yourself. Flask itself, and all the libraries you can find on PyPI are distributed with either setuptools or distutils. In this case we assume your application is called yourapplication.py and you are not using a module, but a package. If you have not yet converted your application into a package, head over to the Larger Applications pattern
120 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
to see how this can be done. A working deployment with setuptools is the first step into more complex and more automated deployment scenarios. If you want to fully automate the process, also read the Deploying with Fabric chapter.
Basic Setup Script
Because you have Flask installed, you have setuptools available on your system. Flask already depends upon setup- tools. Standard disclaimer applies: you better use a virtualenv. Your setup code always goes into a file named setup.py next to your application. The name of the file is only convention, but because everybody will look for a file with that name, you better not change it. A basic setup.py file for a Flask application looks like this:
from setuptools import setup
setup( name='Your Application', version='1.0', long_description=__doc__, packages=['yourapplication'], include_package_data=True, zip_safe=False, install_requires=['Flask'] )
Please keep in mind that you have to list subpackages explicitly. If you want setuptools to lookup the packages for you automatically, you can use the find_packages function:
from setuptools import setup, find_packages
setup( ... packages=find_packages() )
Most parameters to the setup function should be self explanatory, include_package_data and zip_safe might not be. include_package_data tells setuptools to look for a MANIFEST.in file and install all the entries that match as package data. We will use this to distribute the static files and templates along with the Python module (see Distributing Resources). The zip_safe flag can be used to force or prevent zip Archive creation. In general you probably don’t want your packages to be installed as zip files because some tools do not support them and they make debugging a lot harder.
Tagging Builds
It is useful to distinguish between release and development builds. Add a setup.cfg file to configure these options.
[egg_info] tag_build=.dev tag_date=1
[aliases] release= egg_info-Db''
1.21. Patterns for Flask 121 Flask Documentation (1.1.x), Release 1.1.4
Running python setup.py sdist will create a development package with “.dev” and the current date appended: flaskr-1.0.dev20160314.tar.gz. Running python setup.py release sdist will create a release package with only the version: flaskr-1.0.tar.gz.
Distributing Resources
If you try to install the package you just created, you will notice that folders like static or templates are not installed for you. The reason for this is that setuptools does not know which files to add for you. What you should do, is to create a MANIFEST.in file next to your setup.py file. This file lists all the files that should be added to your tarball:
recursive-include yourapplication/templates * recursive-include yourapplication/static *
Don’t forget that even if you enlist them in your MANIFEST.in file, they won’t be installed for you unless you set the include_package_data parameter of the setup function to True!
Declaring Dependencies
Dependencies are declared in the install_requires parameter as a list. Each item in that list is the name of a package that should be pulled from PyPI on installation. By default it will always use the most recent version, but you can also provide minimum and maximum version requirements. Here some examples:
install_requires=[ 'Flask>=0.2', 'SQLAlchemy>=0.6', 'BrokenPackage>=0.7,<=1.0' ]
As mentioned earlier, dependencies are pulled from PyPI. What if you want to depend on a package that cannot be found on PyPI and won’t be because it is an internal package you don’t want to share with anyone? Just do it as if there was a PyPI entry and provide a list of alternative locations where setuptools should look for tarballs:
dependency_links=['http://example.com/yourfiles']
Make sure that page has a directory listing and the links on the page are pointing to the actual tarballs with their correct filenames as this is how setuptools will find the files. If you have an internal company server that contains the packages, provide the URL to that server.
Installing / Developing
To install your application (ideally into a virtualenv) just run the setup.py script with the install parameter. It will install your application into the virtualenv’s site-packages folder and also download and install all dependencies:
$ python setup.py install
If you are developing on the package and also want the requirements to be installed, you can use the develop command instead:
$ python setup.py develop
This has the advantage of just installing a link to the site-packages folder instead of copying the data over. You can then continue to work on the code without having to run install again after each change.
122 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.21.7 Deploying with Fabric
Fabric is a tool for Python similar to Makefiles but with the ability to execute commands on a remote server. In combination with a properly set up Python package (Larger Applications) and a good concept for configurations (Configuration Handling) it is very easy to deploy Flask applications to external servers. Before we get started, here a quick checklist of things we have to ensure upfront: • Fabric 1.0 has to be installed locally. This tutorial assumes the latest version of Fabric. • The application already has to be a package and requires a working setup.py file (Deploying with Setuptools). • In the following example we are using mod_wsgi for the remote servers. You can of course use your own favourite server there, but for this example we chose Apache + mod_wsgi because it’s very easy to setup and has a simple way to reload applications without root access.
Creating the first Fabfile
A fabfile is what controls what Fabric executes. It is named fabfile.py and executed by the fab command. All the functions defined in that file will show up as fab subcommands. They are executed on one or more hosts. These hosts can be defined either in the fabfile or on the command line. In this case we will add them to the fabfile. This is a basic first example that has the ability to upload the current source code to the server and install it into a pre-existing virtual environment:
from fabric.api import *
# the user to use for the remote commands env.user='appuser' # the servers where the commands are executed env.hosts=['server1.example.com','server2.example.com']
def pack(): # build the package local('python setup.py sdist --formats=gztar', capture=False)
def deploy(): # figure out the package name and version dist= local('python setup.py --fullname', capture= True).strip() filename=' %s.tar.gz'% dist
# upload the package to the temporary folder on the server put('dist/%s'% filename,'/tmp/ %s'% filename)
# install the package in the application's virtualenv with pip run('/var/www/yourapplication/env/bin/pip install /tmp/%s'% filename)
# remove the uploaded package run('rm -r /tmp/%s'% filename)
# touch the .wsgi file to trigger a reload in mod_wsgi run('touch /var/www/yourapplication.wsgi')
Running Fabfiles
Now how do you execute that fabfile? You use the fab command. To deploy the current version of the code on the remote server you would use this command:
1.21. Patterns for Flask 123 Flask Documentation (1.1.x), Release 1.1.4
$ fab pack deploy
However this requires that our server already has the /var/www/yourapplication folder created and /var/ www/yourapplication/env to be a virtual environment. Furthermore are we not creating the configuration or .wsgi file on the server. So how do we bootstrap a new server into our infrastructure? This now depends on the number of servers we want to set up. If we just have one application server (which the majority of applications will have), creating a command in the fabfile for this is overkill. But obviously you can do that. In that case you would probably call it setup or bootstrap and then pass the servername explicitly on the command line:
$ fab -H newserver.example.com bootstrap
To setup a new server you would roughly do these steps: 1. Create the directory structure in /var/www:
$ mkdir /var/www/yourapplication $ cd /var/www/yourapplication $ virtualenv --distribute env
2. Upload a new application.wsgi file to the server and the configuration file for the application (eg: application.cfg) 3. Create a new Apache config for yourapplication and activate it. Make sure to activate watching for changes of the .wsgi file so that we can automatically reload the application by touching it. (See mod_wsgi (Apache) for more information) So now the question is, where do the application.wsgi and application.cfg files come from?
The WSGI File
The WSGI file has to import the application and also to set an environment variable so that the application knows where to look for the config. This is a short example that does exactly that:
import os os.environ['YOURAPPLICATION_CONFIG']='/var/www/yourapplication/application.cfg' from yourapplication import app
The application itself then has to initialize itself like this to look for the config at that environment variable:
app= Flask(__name__) app.config.from_object('yourapplication.default_config') app.config.from_envvar('YOURAPPLICATION_CONFIG')
This approach is explained in detail in the Configuration Handling section of the documentation.
The Configuration File
Now as mentioned above, the application will find the correct configuration file by looking up the YOURAPPLICATION_CONFIG environment variable. So we have to put the configuration in a place where the application will able to find it. Configuration files have the unfriendly quality of being different on all computers, so you do not version them usually.
124 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
A popular approach is to store configuration files for different servers in a separate version control repository and check them out on all servers. Then symlink the file that is active for the server into the location where it’s expected (eg: /var/www/yourapplication). Either way, in our case here we only expect one or two servers and we can upload them ahead of time by hand.
First Deployment
Now we can do our first deployment. We have set up the servers so that they have their virtual environments and activated apache configs. Now we can pack up the application and deploy it:
$ fab pack deploy
Fabric will now connect to all servers and run the commands as written down in the fabfile. First it will execute pack so that we have our tarball ready and then it will execute deploy and upload the source code to all servers and install it there. Thanks to the setup.py file we will automatically pull in the required libraries into our virtual environment.
Next Steps
From that point onwards there is so much that can be done to make deployment actually fun: • Create a bootstrap command that initializes new servers. It could initialize a new virtual environment, setup apache appropriately etc. • Put configuration files into a separate version control repository and symlink the active configs into place. • You could also put your application code into a repository and check out the latest version on the server and then install. That way you can also easily go back to older versions. • hook in testing functionality so that you can deploy to an external server and run the test suite. Working with Fabric is fun and you will notice that it’s quite magical to type fab deploy and see your application being deployed automatically to one or more remote servers.
1.21.8 Using SQLite 3 with Flask
In Flask you can easily implement the opening of database connections on demand and closing them when the context dies (usually at the end of the request). Here is a simple example of how you can use SQLite 3 with Flask:
import sqlite3 from flask import g
DATABASE='/path/to/database.db'
def get_db(): db= getattr(g,'_database', None) if db is None: db=g._database= sqlite3.connect(DATABASE) return db
@app.teardown_appcontext def close_connection(exception): db= getattr(g,'_database', None) if db is not None: db.close()
1.21. Patterns for Flask 125 Flask Documentation (1.1.x), Release 1.1.4
Now, to use the database, the application must either have an active application context (which is always true if there is a request in flight) or create an application context itself. At that point the get_db function can be used to get the current database connection. Whenever the context is destroyed the database connection will be terminated. Note: if you use Flask 0.9 or older you need to use flask._app_ctx_stack.top instead of g as the flask.g object was bound to the request and not application context. Example:
@app.route('/') def index(): cur= get_db().cursor() ...
Note: Please keep in mind that the teardown request and appcontext functions are always executed, even if a before- request handler failed or was never executed. Because of this we have to make sure here that the database is there before we close it.
Connect on Demand
The upside of this approach (connecting on first use) is that this will only open the connection if truly necessary. If you want to use this code outside a request context you can use it in a Python shell by opening the application context by hand:
with app.app_context(): # now you can use get_db()
Easy Querying
Now in each request handling function you can access get_db() to get the current open database connection. To simplify working with SQLite, a row factory function is useful. It is executed for every result returned from the database to convert the result. For instance, in order to get dictionaries instead of tuples, this could be inserted into the get_db function we created above:
def make_dicts(cursor, row): return dict((cursor.description[idx][0], value) for idx, value in enumerate(row))
db.row_factory= make_dicts
This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in get_db instead:
db.row_factory= sqlite3.Row
This would use Row objects rather than dicts to return the results of queries. These are namedtuple s, so we can access them either by index or by key. For example, assuming we have a sqlite3.Row called r for the rows id, FirstName, LastName, and MiddleInitial:
>>> # You can get values based on the row's name >>> r['FirstName'] John >>> # Or, you can get them based on index (continues on next page)
126 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) >>> r[1] John # Row objects are also iterable: >>> for value in r: ... print(value) 1 John Doe M
Additionally, it is a good idea to provide a query function that combines getting the cursor, executing and fetching the results:
def query_db(query, args=(), one=False): cur= get_db().execute(query, args) rv= cur.fetchall() cur.close() return (rv[0] if rv else None) if one else rv
This handy little function, in combination with a row factory, makes working with the database much more pleasant than it is by just using the raw cursor and connection objects. Here is how you can use it:
for user in query_db('select * from users'): print user['username'],'has the id', user['user_id']
Or if you just want a single result:
user= query_db('select * from users where username = ?', [the_username], one=True) if user is None: print'No such user' else: print the_username,'has the id', user['user_id']
To pass variable parts to the SQL statement, use a question mark in the statement and pass in the arguments as a list. Never directly add them to the SQL statement with string formatting because this makes it possible to attack the application using SQL Injections.
Initial Schemas
Relational databases need schemas, so applications often ship a schema.sql file that creates the database. It’s a good idea to provide a function that creates the database based on that schema. This function can do that for you:
def init_db(): with app.app_context(): db= get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()
You can then create such a database from the Python shell:
>>> from yourapplication import init_db >>> init_db()
1.21. Patterns for Flask 127 Flask Documentation (1.1.x), Release 1.1.4
1.21.9 SQLAlchemy in Flask
Many people prefer SQLAlchemy for database access. In this case it’s encouraged to use a package instead of a module for your flask application and drop the models into a separate module (Larger Applications). While that is not necessary, it makes a lot of sense. There are four very common ways to use SQLAlchemy. I will outline each of them here:
Flask-SQLAlchemy Extension
Because SQLAlchemy is a common database abstraction layer and object relational mapper that requires a little bit of configuration effort, there is a Flask extension that handles that for you. This is recommended if you want to get started quickly. You can download Flask-SQLAlchemy from PyPI.
Declarative
The declarative extension in SQLAlchemy is the most recent method of using SQLAlchemy. It allows you to define tables and models in one go, similar to how Django works. In addition to the following text I recommend the official documentation on the declarative extension. Here’s the example database.py module for your application:
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base
engine= create_engine('sqlite:////tmp/test.db', convert_unicode= True) db_session= scoped_session(sessionmaker(autocommit= False, autoflush=False, bind=engine)) Base= declarative_base() Base.query= db_session.query_property() def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import yourapplication.models Base.metadata.create_all(bind=engine)
To define your models, just subclass the Base class that was created by the code above. If you are wondering why we don’t have to care about threads here (like we did in the SQLite3 example above with the g object): that’s because SQLAlchemy does that for us already with the scoped_session. To use SQLAlchemy in a declarative way with your application, you just have to put the following code into your application module. Flask will automatically remove database sessions at the end of the request or when the application shuts down:
from yourapplication.database import db_session
@app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
Here is an example model (put this into models.py, e.g.):
128 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
from sqlalchemy import Column, Integer, String from yourapplication.database import Base class User(Base): __tablename__='users' id= Column(Integer, primary_key= True) name= Column(String(50), unique= True) email= Column(String(120), unique= True)
def __init__(self, name=None, email=None): self.name= name self.email= email
def __repr__(self): return '
To create the database you can use the init_db function:
>>> from yourapplication.database import init_db >>> init_db()
You can insert entries into the database like this:
>>> from yourapplication.database import db_session >>> from yourapplication.models import User >>> u= User('admin','admin@localhost') >>> db_session.add(u) >>> db_session.commit()
Querying is simple as well:
>>> User.query.all() [
Manual Object Relational Mapping
Manual object relational mapping has a few upsides and a few downsides versus the declarative approach from above. The main difference is that you define tables and classes separately and map them together. It’s more flexible but a little more to type. In general it works like the declarative approach, so make sure to also split up your application into multiple modules in a package. Here is an example database.py module for your application: from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import scoped_session, sessionmaker engine= create_engine('sqlite:////tmp/test.db', convert_unicode= True) metadata= MetaData() db_session= scoped_session(sessionmaker(autocommit= False, autoflush=False, bind=engine)) def init_db(): metadata.create_all(bind=engine)
1.21. Patterns for Flask 129 Flask Documentation (1.1.x), Release 1.1.4
As in the declarative approach, you need to close the session after each request or application context shutdown. Put this into your application module: from yourapplication.database import db_session
@app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
Here is an example table and model (put this into models.py): from sqlalchemy import Table, Column, Integer, String from sqlalchemy.orm import mapper from yourapplication.database import metadata, db_session class User(object): query= db_session.query_property()
def __init__(self, name=None, email=None): self.name= name self.email= email
def __repr__(self): return '
Querying and inserting works exactly the same as in the example above.
SQL Abstraction Layer
If you just want to use the database system (and SQL) abstraction layer you basically only need the engine: from sqlalchemy import create_engine, MetaData, Table engine= create_engine('sqlite:////tmp/test.db', convert_unicode= True) metadata= MetaData(bind=engine)
Then you can either declare the tables in your code like in the examples above, or automatically load them: from sqlalchemy import Table users= Table('users', metadata, autoload= True)
To insert data you can use the insert method. We have to get a connection first so that we can use a transaction:
>>> con= engine.connect() >>> con.execute(users.insert(), name='admin', email='admin@localhost')
SQLAlchemy will automatically commit for us. To query your database, you use the engine directly or use a connection:
130 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
>>> users.select(users.c.id ==1).execute().first() (1, u'admin', u'admin@localhost')
These results are also dict-like tuples:
>>> r= users.select(users.c.id ==1).execute().first() >>> r['name'] u'admin'
You can also pass strings of SQL statements to the execute() method:
>>> engine.execute('select * from users where id = :1',[1]).first() (1, u'admin', u'admin@localhost')
For more information about SQLAlchemy, head over to the website.
1.21.10 Uploading Files
Ah yes, the good old problem of file uploads. The basic idea of file uploads is actually quite simple. It basically works like this: 1.A
'''So what does that secure_filename() function actually do? Now the problem is that there is that principle called “never trust user input”. This is also true for the filename of an uploaded file. All submitted form data can be forged, and filenames can be dangerous. For the moment just remember: always use that function to secure a filename before storing it directly on the filesystem.
Information for the Pros So you’re interested in what that secure_filename() function does and what the problem is if you’re not using it? So just imagine someone would send the following information as filename to your application: filename="../../../../home/username/.bashrc"
Assuming the number of ../ is correct and you would join this with the UPLOAD_FOLDER the user might have the ability to modify a file on the server’s filesystem he or she should not modify. This does require some knowledge about how the application looks like, but trust me, hackers are patient :) Now let’s look how that function works:
>>> secure_filename('../../../../home/username/.bashrc') 'home_username_.bashrc'
Now one last thing is missing: the serving of the uploaded files. In the upload_file() we redirect the user to url_for('uploaded_file', filename=filename), that is, /uploads/filename. So we write the uploaded_file() function to return the file of that name. As of Flask 0.5 we can use a function that does that for
132 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
us:
from flask import send_from_directory
@app.route('/uploads/
Alternatively you can register uploaded_file as build_only rule and use the SharedDataMiddleware. This also works with older versions of Flask:
from werkzeug.middleware.shared_data import SharedDataMiddleware app.add_url_rule('/uploads/
If you now run the application everything should work as expected.
Improving Uploads
New in version 0.6. So how exactly does Flask handle uploads? Well it will store them in the webserver’s memory if the files are reasonable small otherwise in a temporary location (as returned by tempfile.gettempdir()). But how do you specify the maximum file size after which an upload is aborted? By default Flask will happily accept file uploads to an unlimited amount of memory, but you can limit that by setting the MAX_CONTENT_LENGTH config key:
from flask import Flask, Request
app= Flask(__name__) app.config['MAX_CONTENT_LENGTH']= 16 * 1024 * 1024
The code above will limit the maximum allowed payload to 16 megabytes. If a larger file is transmitted, Flask will raise a RequestEntityTooLarge exception.
Connection Reset Issue When using the local development server, you may get a connection reset error instead of a 413 response. You will get the correct status response when running the app with a production WSGI server.
This feature was added in Flask 0.6 but can be achieved in older versions as well by subclassing the request object. For more information on that consult the Werkzeug documentation on file handling.
Upload Progress Bars
A while ago many developers had the idea to read the incoming file in small chunks and store the upload progress in the database to be able to poll the progress with JavaScript from the client. Long story short: the client asks the server every 5 seconds how much it has transmitted already. Do you realize the irony? The client is asking for something it should already know.
1.21. Patterns for Flask 133 Flask Documentation (1.1.x), Release 1.1.4
An Easier Solution
Now there are better solutions that work faster and are more reliable. There are JavaScript libraries like jQuery that have form plugins to ease the construction of progress bar. Because the common pattern for file uploads exists almost unchanged in all applications dealing with uploads, there is also a Flask extension called Flask-Uploads that implements a full fledged upload mechanism with white and blacklisting of extensions and more.
1.21.11 Caching
When your application runs slow, throw some caches in. Well, at least it’s the easiest way to speed up things. What does a cache do? Say you have a function that takes some time to complete but the results would still be good enough if they were 5 minutes old. So then the idea is that you actually put the result of that calculation into a cache for some time. Flask itself does not provide caching for you, but Flask-Caching, an extension for Flask does. Flask-Caching supports various backends, and it is even possible to develop your own caching backend.
1.21.12 View Decorators
Python has a really interesting feature called function decorators. This allows some really neat things for web applica- tions. Because each view in Flask is a function, decorators can be used to inject additional functionality to one or more functions. The route() decorator is the one you probably used already. But there are use cases for implementing your own decorator. For instance, imagine you have a view that should only be used by people that are logged in. If a user goes to the site and is not logged in, they should be redirected to the login page. This is a good example of a use case where a decorator is an excellent solution.
Login Required Decorator
So let’s implement such a decorator. A decorator is a function that wraps and replaces another function. Since the original function is replaced, you need to remember to copy the original function’s information to the new function. Use functools.wraps() to handle this for you. This example assumes that the login page is called 'login' and that the current user is stored in g.user and is None if there is no-one logged in.
from functools import wraps from flask import g, request, redirect, url_for
def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.user is None: return redirect(url_for('login', next=request.url)) return f(*args, **kwargs) return decorated_function
To use the decorator, apply it as innermost decorator to a view function. When applying further decorators, always remember that the route() decorator is the outermost.
@app.route('/secret_page') @login_required (continues on next page)
134 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def secret_page(): pass
Note: The next value will exist in request.args after a GET request for the login page. You’ll have to pass it along when sending the POST request from the login form. You can do this with a hidden input tag, then retrieve it from request.form when logging the user in.
Caching Decorator
Imagine you have a view function that does an expensive calculation and because of that you would like to cache the generated results for a certain amount of time. A decorator would be nice for that. We’re assuming you have set up a cache like mentioned in Caching. Here is an example cache function. It generates the cache key from a specific prefix (actually a format string) and the current path of the request. Notice that we are using a function that first creates the decorator that then decorates the function. Sounds awful? Unfortunately it is a little bit more complex, but the code should still be straightforward to read. The decorated function will then work as follows 1. get the unique cache key for the current request based on the current path. 2. get the value for that key from the cache. If the cache returned something we will return that value. 3. otherwise the original function is called and the return value is stored in the cache for the timeout provided (by default 5 minutes). Here the code: from functools import wraps from flask import request def cached(timeout=5 * 60, key='view/%s'): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): cache_key= key% request.path rv= cache.get(cache_key) if rv is not None: return rv rv= f( *args, **kwargs) cache.set(cache_key, rv, timeout=timeout) return rv return decorated_function return decorator
Notice that this assumes an instantiated cache object is available, see Caching for more information.
Templating Decorator
A common pattern invented by the TurboGears guys a while back is a templating decorator. The idea of that decorator is that you return a dictionary with the values passed to the template from the view function and the template is
1.21. Patterns for Flask 135 Flask Documentation (1.1.x), Release 1.1.4
automatically rendered. With that, the following three examples do exactly the same:
@app.route('/') def index(): return render_template('index.html', value=42)
@app.route('/') @templated('index.html') def index(): return dict(value=42)
@app.route('/') @templated() def index(): return dict(value=42)
As you can see, if no template name is provided it will use the endpoint of the URL map with dots converted to slashes + '.html'. Otherwise the provided template name is used. When the decorated function returns, the dictionary re- turned is passed to the template rendering function. If None is returned, an empty dictionary is assumed, if something else than a dictionary is returned we return it from the function unchanged. That way you can still use the redirect function or return simple strings. Here is the code for that decorator:
from functools import wraps from flask import request, render_template
def templated(template=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): template_name= template if template_name is None: template_name= request.endpoint \ .replace('.','/')+'.html' ctx= f( *args, **kwargs) if ctx is None: ctx={} elif not isinstance(ctx, dict): return ctx return render_template(template_name, **ctx) return decorated_function return decorator
Endpoint Decorator
When you want to use the werkzeug routing system for more flexibility you need to map the endpoint as defined in the Rule to a view function. This is possible with this decorator. For example:
from flask import Flask from werkzeug.routing import Rule
app= Flask(__name__) app.url_map.add(Rule('/', endpoint='index'))
@app.endpoint('index') (continues on next page)
136 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def my_index(): return "Hello world"
1.21.13 Form Validation with WTForms
When you have to work with form data submitted by a browser view, code quickly becomes very hard to read. There are libraries out there designed to make this process easier to manage. One of them is WTForms which we will handle here. If you find yourself in the situation of having many forms, you might want to give it a try. When you are working with WTForms you have to define your forms as classes first. I recommend breaking up the application into multiple modules (Larger Applications) for that and adding a separate module for the forms.
Getting the most out of WTForms with an Extension The Flask-WTF extension expands on this pattern and adds a few little helpers that make working with forms and Flask more fun. You can get it from PyPI.
The Forms
This is an example form for a typical registration page: from wtforms import Form, BooleanField, StringField, PasswordField, validators class RegistrationForm(Form): username= StringField('Username', [validators.Length(min=4, max=25)]) email= StringField('Email Address', [validators.Length(min=6, max=35)]) password= PasswordField('New Password',[ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm= PasswordField('Repeat Password') accept_tos= BooleanField('I accept the TOS', [validators.DataRequired()])
In the View
In the view function, the usage of this form looks like this:
@app.route('/register', methods=['GET','POST']) def register(): form= RegistrationForm(request.form) if request.method =='POST' and form.validate(): user= User(form.username.data, form.email.data, form.password.data) db_session.add(user) flash('Thanks for registering') return redirect(url_for('login')) return render_template('register.html', form=form)
Notice we’re implying that the view is using SQLAlchemy here (SQLAlchemy in Flask), but that’s not a requirement, of course. Adapt the code as necessary. Things to remember:
1.21. Patterns for Flask 137 Flask Documentation (1.1.x), Release 1.1.4
1. create the form from the request form value if the data is submitted via the HTTP POST method and args if the data is submitted as GET. 2. to validate the data, call the validate() method, which will return True if the data validates, False otherwise. 3. to access individual values from the form, access form.
Forms in Templates
Now to the template side. When you pass the form to the templates, you can easily render them there. Look at the following example template to see how easy this is. WTForms does half the form generation for us already. To make it even nicer, we can write a macro that renders a field with label and a list of errors if there are any. Here’s an example _formhelpers.html template with such a macro:
{% macro render_field(field) %}
- {% for error in field.errors %}
- {{ error }} {% endfor %}
This macro accepts a couple of keyword arguments that are forwarded to WTForm’s field function, which ren- ders the field for us. The keyword arguments will be inserted as HTML attributes. So, for example, you can call render_field(form.username, class='username') to add a class to the input element. Note that WT- Forms returns standard Python unicode strings, so we have to tell Jinja2 that this data is already HTML-escaped with the |safe filter. Here is the register.html template for the function we used above, which takes advantage of the _formhelpers.html template:
{% from "_formhelpers.html" import render_field %}
For more information about WTForms, head over to the WTForms website.
1.21.14 Template Inheritance
The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.
138 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Sounds complicated but is very basic. It’s easiest to understand it by starting with an example.
Base Template
This template, which we’ll call layout.html, defines a simple HTML skeleton document that you might use for a simple two-column page. It’s the job of “child” templates to fill the empty blocks with content:
{% block head %}
In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is tell the template engine that a child template may override those portions of the template.
Child Template
A child template might look like this:
{% extends "layout.html" %} {% block title %}Index{% endblock %} {% block head %} {{ super() }} {% endblock %} {% block content %}
Index
Welcome on my awesome homepage. {% endblock %}
The {% extends %} tag is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this template, first it locates the parent. The extends tag must be the first tag in the template. To render the contents of a block defined in the parent template, use {{ super() }}.
1.21.15 Message Flashing
Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it next
1.21. Patterns for Flask 139 Flask Documentation (1.1.x), Release 1.1.4 request and only next request. This is usually combined with a layout template that does this. Note that browsers and sometimes web servers enforce a limit on cookie sizes. This means that flashing messages that are too large for session cookies causes message flashing to fail silently.
Simple Flashing
So here is a full example: from flask import Flask, flash, redirect, render_template, \ request, url_for app= Flask(__name__) app.secret_key=b'_5#y2L"F4Q8z \n\xec]/'
@app.route('/') def index(): return render_template('index.html')
@app.route('/login', methods=['GET','POST']) def login(): error= None if request.method =='POST': if request.form['username'] !='admin' or \ request.form['password'] !='secret': error='Invalid credentials' else: flash('You were successfully logged in') return redirect(url_for('index')) return render_template('login.html', error=error)
And here is the layout.html template which does the magic:
- {% for message in messages %}
- {{ message }} {% endfor %}
Here is the index.html template which inherits from layout.html:
{% extends "layout.html" %} {% block body %}
Overview
Do you want to log in? {% endblock %}
And here is the login.html template which also inherits from layout.html:
{% extends "layout.html" %} {% block body %} (continues on next page)
140 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page)
Login
{% if error %}Error: {{ error }} {% endif %}
{% endblock %}Flashing With Categories
New in version 0.3. It is also possible to provide categories when flashing a message. The default category if nothing is provided is 'message'. Alternative categories can be used to give the user better feedback. For example error messages could be displayed with a red background. To flash a message with a different category, just use the second argument to the flash() function: flash(u'Invalid password provided','error')
Inside the template you then have to tell the get_flashed_messages() function to also return the categories. The loop looks slightly different in that situation then:
{% with messages= get_flashed_messages(with_categories= true) %} {% if messages %}
- {% for category, message in messages %}
- {{ message }} {% endfor %}
This is just one example of how to render these flashed messages. One might also use the category to add a prefix such as Error: to the message.
Filtering Flash Messages
New in version 0.9. Optionally you can pass a list of categories which filters the results of get_flashed_messages(). This is useful if you wish to render each category in a separate block.
{% with errors= get_flashed_messages(category_filter=["error"]) %} {% if errors %}
{% endif %} {% endwith %}1.21.16 AJAX with jQuery jQuery is a small JavaScript library commonly used to simplify working with the DOM and JavaScript in general. It is the perfect tool to make web applications more dynamic by exchanging JSON between server and client. JSON itself is a very lightweight transport format, very similar to how Python primitives (numbers, strings, dicts and lists) look like which is widely supported and very easy to parse. It became popular a few years ago and quickly replaced XML as transport format in web applications.
Loading jQuery
In order to use jQuery, you have to download it first and place it in the static folder of your application and then ensure it’s loaded. Ideally you have a layout template that is used for all pages where you just have to add a script statement to the bottom of your
to load jQuery:Another method is using Google’s AJAX Libraries API to load jQuery:
In this case you have to put jQuery into your static folder as a fallback, but it will first try to load it directly from Google. This has the advantage that your website will probably load faster for users if they went to at least one other website before using the same jQuery version from Google because it will already be in the browser cache.
Where is My Site?
Do you know where your application is? If you are developing the answer is quite simple: it’s on localhost port something and directly on the root of that server. But what if you later decide to move your application to a different location? For example to http://example.com/myapp? On the server side this never was a problem because we were using the handy url_for() function that could answer that question for us, but if we are using jQuery we should not hardcode the path to the application but make that dynamic, so how can we do that? A simple method would be to add a script tag to our page that sets a global variable to the prefix to the root of the application. Something like this:
142 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
The |safe is necessary in Flask before 0.10 so that Jinja does not escape the JSON encoded string with HTML rules. Usually this would be necessary, but we are inside a script block here where different rules apply.
Information for Pros In HTML the script tag is declared CDATA which means that entities will not be parsed. Everything until script> is handled as script. This also means that there must never be any between the script tags. |tojson is kind enough to do the right thing here and escape slashes for you ({{ ""|tojson|safe }} is rendered as "<\/script>"). In Flask 0.10 it goes a step further and escapes all HTML tags with unicode escapes. This makes it possible for Flask to automatically mark the result as HTML safe.
JSON View Functions
Now let’s create a server side function that accepts two URL arguments of numbers which should be added together and then sent back to the application in a JSON object. This is a really ridiculous example and is something you usually would do on the client side alone, but a simple example that shows how you would use jQuery and Flask nonetheless:
from flask import Flask, jsonify, render_template, request app= Flask(__name__)
@app.route('/_add_numbers') def add_numbers(): a= request.args.get('a',0, type=int) b= request.args.get('b',0, type=int) return jsonify(result=a+ b)
@app.route('/') def index(): return render_template('index.html')
As you can see I also added an index method here that renders a template. This template will load jQuery as above and have a little form where we can add two numbers and a link to trigger the function on the server side. Note that we are using the get() method here which will never fail. If the key is missing a default value (here 0) is returned. Furthermore it can convert values to a specific type (like in our case int). This is especially handy for code that is triggered by a script (APIs, JavaScript etc.) because you don’t need special error reporting in that case.
The HTML
Your index.html template either has to extend a layout.html template with jQuery loaded and the $SCRIPT_ROOT variable set, or do that on the top. Here’s the HTML code needed for our little application (index.html). Notice that we also drop the script directly into the HTML here. It is usually a better idea to have that in a separate script file:
jQuery Example
+ = ?
I won’t go into detail here about how jQuery works, just a very quick explanation of the little bit of code above: 1. $(function() { ... }) specifies code that should run once the browser is done loading the basic parts of the page. 2. $('selector') selects an element and lets you operate on it. 3. element.bind('event', func) specifies a function that should run when the user clicked on the ele- ment. If that function returns false, the default behavior will not kick in (in this case, navigate to the # URL). 4. $.getJSON(url, data, func) sends a GET request to url and will send the contents of the data object as query parameters. Once the data arrived, it will call the given function with the return value as argument. Note that we can use the $SCRIPT_ROOT variable here that we set earlier. Check out the example source for a full application demonstrating the code on this page, as well as the same thing using XMLHttpRequest and fetch.
1.21.17 Custom Error Pages
Flask comes with a handy abort() function that aborts a request with an HTTP error code early. It will also provide a plain black and white error page for you with a basic description, but nothing fancy. Depending on the error code it is less or more likely for the user to actually see such an error.
Common Error Codes
The following error codes are some that are often displayed to the user, even if the application behaves correctly: 404 Not Found The good old “chap, you made a mistake typing that URL” message. So common that even novices to the internet know that 404 means: damn, the thing I was looking for is not there. It’s a very good idea to make sure there is actually something useful on a 404 page, at least a link back to the index. 403 Forbidden If you have some kind of access control on your website, you will have to send a 403 code for disal- lowed resources. So make sure the user is not lost when they try to access a forbidden resource. 410 Gone Did you know that there the “404 Not Found” has a brother named “410 Gone”? Few people actually implement that, but the idea is that resources that previously existed and got deleted answer with 410 instead of 404. If you are not deleting documents permanently from the database but just mark them as deleted, do the user a favour and use the 410 code instead and display a message that what they were looking for was deleted for all eternity. 500 Internal Server Error Usually happens on programming errors or if the server is overloaded. A terribly good idea is to have a nice page there, because your application will fail sooner or later (see also: Application Errors).
144 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Error Handlers
An error handler is a function that returns a response when a type of error is raised, similar to how a view is a function that returns a response when a request URL is matched. It is passed the instance of the error being handled, which is most likely a HTTPException. An error handler for “500 Internal Server Error” will be passed uncaught exceptions in addition to explicit 500 errors. An error handler is registered with the errorhandler() decorator or the register_error_handler() method. A handler can be registered for a status code, like 404, or for an exception class. The status code of the response will not be set to the handler’s code. Make sure to provide the appropriate HTTP status code when returning a response from a handler. A handler for “500 Internal Server Error” will not be used when running in debug mode. Instead, the interactive debugger will be shown. Here is an example implementation for a “404 Page Not Found” exception:
from flask import render_template
@app.errorhandler(404) def page_not_found(e): # note that we set the 404 status explicitly return render_template('404.html'), 404
When using the application factory pattern:
from flask import Flask, render_template
def page_not_found(e): return render_template('404.html'), 404 def create_app(config_filename): app= Flask(__name__) app.register_error_handler(404, page_not_found) return app
An example template might be this:
{% extends "layout.html" %} {% block title %}Page Not Found{% endblock %} {% block body %}
Page Not Found
What you were looking for is just not there.
go somewhere nice {% endblock %}
Returning API errors as JSON
When using Flask for web APIs, you can use the same techniques as above to return JSON responses to API errors. abort() is called with a description parameter. The errorhandler() will use that as the JSON error message, and set the status code to 404.
from flask import abort, jsonify
@app.errorhandler(404) def resource_not_found(e): (continues on next page)
1.21. Patterns for Flask 145 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) return jsonify(error=str(e)), 404
@app.route("/cheese") def get_one_cheese(): resource= get_resource()
if resource is None: abort(404, description="Resource not found")
return jsonify(resource)
1.21.18 Lazily Loading Views
Flask is usually used with the decorators. Decorators are simple and you have the URL right next to the function that is called for that specific URL. However there is a downside to this approach: it means all your code that uses decorators has to be imported upfront or Flask will never actually find your function. This can be a problem if your application has to import quick. It might have to do that on systems like Google’s App Engine or other systems. So if you suddenly notice that your application outgrows this approach you can fall back to a centralized URL mapping. The system that enables having a central URL map is the add_url_rule() function. Instead of using decorators, you have a file that sets up the application with all URLs.
Converting to Centralized URL Map
Imagine the current application looks somewhat like this:
from flask import Flask app= Flask(__name__)
@app.route('/') def index(): pass
@app.route('/user/
Then, with the centralized approach you would have one file with the views (views.py) but without any decorator:
def index(): pass
def user(username): pass
And then a file that sets up an application which maps the functions to URLs:
from flask import Flask from yourapplication import views app= Flask(__name__) app.add_url_rule('/', view_func=views.index) app.add_url_rule('/user/
146 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Loading Late
So far we only split up the views and the routing, but the module is still loaded upfront. The trick is to actually load the view function as needed. This can be accomplished with a helper class that behaves just like a function but internally imports the real function on first use:
from werkzeug.utils import import_string, cached_property
class LazyView(object):
def __init__(self, import_name): self.__module__, self.__name__= import_name.rsplit('.',1) self.import_name= import_name
@cached_property def view(self): return import_string(self.import_name)
def __call__(self, *args, **kwargs): return self.view(*args, **kwargs)
What’s important here is is that __module__ and __name__ are properly set. This is used by Flask internally to figure out how to name the URL rules in case you don’t provide a name for the rule yourself. Then you can define your central place to combine the views like this:
from flask import Flask from yourapplication.helpers import LazyView app= Flask(__name__) app.add_url_rule('/', view_func=LazyView('yourapplication.views.index')) app.add_url_rule('/user/
You can further optimize this in terms of amount of keystrokes needed to write this by having a function that calls into add_url_rule() by prefixing a string with the project name and a dot, and by wrapping view_func in a LazyView as needed.
def url(import_name, url_rules=[], **options): view= LazyView('yourapplication.'+ import_name) for url_rule in url_rules: app.add_url_rule(url_rule, view_func=view, **options)
# add a single route to the index view url('views.index',['/'])
# add two routes to a single function endpoint url_rules=['/user/','/user/
One thing to keep in mind is that before and after request handlers have to be in a file that is imported upfront to work properly on the first request. The same goes for any kind of remaining decorator.
1.21.19 MongoDB with MongoEngine
Using a document database like MongoDB is a common alternative to relational SQL databases. This pattern shows how to use MongoEngine, a document mapper library, to integrate with MongoDB.
1.21. Patterns for Flask 147 Flask Documentation (1.1.x), Release 1.1.4
A running MongoDB server and Flask-MongoEngine are required.
pip install flask-mongoengine
Configuration
Basic setup can be done by defining MONGODB_SETTINGS on app.config and creating a MongoEngine in- stance.
from flask import Flask from flask_mongoengine import MongoEngine app= Flask(__name__) app.config['MONGODB_SETTINGS']={ "db":"myapp", } db= MongoEngine(app)
Mapping Documents
To declare a model that represents a Mongo document, create a class that inherits from Document and declare each of the fields.
import mongoengine as me
class Movie(me.Document): title= me.StringField(required= True) year= me.IntField() rated= me.StringField() director= me.StringField() actors= me.ListField()
If the document has nested fields, use EmbeddedDocument to defined the fields of the embedded document and EmbeddedDocumentField to declare it on the parent document.
class Imdb(me.EmbeddedDocument): imdb_id= me.StringField() rating= me.DecimalField() votes= me.IntField()
class Movie(me.Document): ... imdb= me.EmbeddedDocumentField(Imdb)
Creating Data
Instantiate your document class with keyword arguments for the fields. You can also assign values to the field attributes after instantiation. Then call doc.save().
bttf= Movie(title="Back To The Future", year=1985) bttf.actors=[ "Michael J. Fox", "Christopher Lloyd" (continues on next page)
148 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) ] bttf.imdb= Imdb(imdb_id="tt0088763", rating=8.5) bttf.save()
Queries
Use the class objects attribute to make queries. A keyword argument looks for an equal value on the field.
bttf= Movies.objects(title="Back To The Future").get_or_404()
Query operators may be used by concatenating them with the field name using a double-underscore. objects, and queries returned by calling it, are iterable.
some_theron_movie= Movie.objects(actors__in=["Charlize Theron"]).first()
for recents in Movie.objects(year__gte=2017): print(recents.title)
Documentation
There are many more ways to define and query documents with MongoEngine. For more information, check out the official documentation. Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check out their documentation as well.
1.21.20 Adding a favicon
A “favicon” is an icon used by browsers for tabs and bookmarks. This helps to distinguish your website and to give it a unique brand. A common question is how to add a favicon to a Flask application. First, of course, you need an icon. It should be 16 × 16 pixels and in the ICO file format. This is not a requirement but a de-facto standard supported by all relevant browsers. Put the icon in your static directory as favicon.ico. Now, to get browsers to find your icon, the correct way is to add a link tag in your HTML. So, for example:
That’s all you need for most browsers, however some really old ones do not support this standard. The old de-facto standard is to serve this file, with this name, at the website root. If your application is not mounted at the root path of the domain you either need to configure the web server to serve the icon at the root or if you can’t do that you’re out of luck. If however your application is the root you can simply route a redirect:
app.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon.ico'))
If you want to save the extra redirect request you can also write a view using send_from_directory():
import os from flask import send_from_directory
@app.route('/favicon.ico') (continues on next page)
1.21. Patterns for Flask 149 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def favicon(): return send_from_directory(os.path.join(app.root_path,'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
We can leave out the explicit mimetype and it will be guessed, but we may as well specify it to avoid the extra guessing, as it will always be the same. The above will serve the icon via your application and if possible it’s better to configure your dedicated web server to serve it; refer to the web server’s documentation.
See also
• The Favicon article on Wikipedia
1.21.21 Streaming Contents
Sometimes you want to send an enormous amount of data to the client, much more than you want to keep in memory. When you are generating the data on the fly though, how do you send that back to the client without the roundtrip to the filesystem? The answer is by using generators and direct responses.
Basic Usage
This is a basic view function that generates a lot of CSV data on the fly. The trick is to have an inner function that uses a generator to generate data and to then invoke that function and pass it to a response object:
from flask import Response
@app.route('/large.csv') def generate_large_csv(): def generate(): for row in iter_all_rows(): yield ','.join(row)+' \n' return Response(generate(), mimetype='text/csv')
Each yield expression is directly sent to the browser. Note though that some WSGI middlewares might break streaming, so be careful there in debug environments with profilers and other things you might have enabled.
Streaming from Templates
The Jinja2 template engine also supports rendering templates piece by piece. This functionality is not directly exposed by Flask because it is quite uncommon, but you can easily do it yourself:
from flask import Response
def stream_template(template_name, **context): app.update_template_context(context) t= app.jinja_env.get_template(template_name) rv=t.stream(context) rv.enable_buffering(5) return rv (continues on next page)
150 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page)
@app.route('/my-large-page.html') def render_large_template(): rows= iter_all_rows() return Response(stream_template('the_template.html', rows=rows))
The trick here is to get the template object from the Jinja2 environment on the application and to call stream() instead of render() which returns a stream object instead of a string. Since we’re bypassing the Flask template render functions and using the template object itself we have to make sure to update the render context ourselves by calling update_template_context(). The template is then evaluated as the stream is iterated over. Since each time you do a yield the server will flush the content to the client you might want to buffer up a few items in the template which you can do with rv.enable_buffering(size). 5 is a sane default.
Streaming with Context
New in version 0.9. Note that when you stream data, the request context is already gone the moment the function executes. Flask 0.9 provides you with a helper that can keep the request context around during the execution of the generator:
from flask import stream_with_context, request, Response
@app.route('/stream') def streamed_response(): def generate(): yield 'Hello' yield request.args['name'] yield '!' return Response(stream_with_context(generate()))
Without the stream_with_context() function you would get a RuntimeError at that point.
1.21.22 Deferred Request Callbacks
One of the design principles of Flask is that response objects are created and passed down a chain of potential callbacks that can modify them or replace them. When the request handling starts, there is no response object yet. It is created as necessary either by a view function or by some other component in the system. What happens if you want to modify the response at a point where the response does not exist yet? A common example for that would be a before_request() callback that wants to set a cookie on the response object. One way is to avoid the situation. Very often that is possible. For instance you can try to move that logic into a after_request() callback instead. However, sometimes moving code there makes it more more complicated or awkward to reason about. As an alternative, you can use after_this_request() to register callbacks that will execute after only the current request. This way you can defer code execution from anywhere in the application, based on the current request. At any time during a request, we can register a function to be called at the end of the request. For example you can remember the current language of the user in a cookie in a before_request() callback:
from flask import request, after_this_request
@app.before_request (continues on next page)
1.21. Patterns for Flask 151 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) def detect_user_language(): language= request.cookies.get('user_lang')
if language is None: language= guess_language_from_request()
# when the response exists, set a cookie with the language @after_this_request def remember_language(response): response.set_cookie('user_lang', language) return response
g.language= language
1.21.23 Adding HTTP Method Overrides
Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP methods (such as PATCH). In that case it’s possible to “proxy” HTTP methods through another HTTP method in total violation of the protocol. The way this works is by letting the client do an HTTP POST request and set the X-HTTP-Method-Override header. Then the method is replaced with the header value before being passed to Flask. This can be accomplished with an HTTP middleware: class HTTPMethodOverrideMiddleware(object): allowed_methods= frozenset([ 'GET', 'HEAD', 'POST', 'DELETE', 'PUT', 'PATCH', 'OPTIONS' ]) bodyless_methods= frozenset(['GET','HEAD','OPTIONS','DELETE'])
def __init__(self, app): self.app= app
def __call__(self, environ, start_response): method= environ.get('HTTP_X_HTTP_METHOD_OVERRIDE','').upper() if method in self.allowed_methods: environ['REQUEST_METHOD']= method if method in self.bodyless_methods: environ['CONTENT_LENGTH']='0' return self.app(environ, start_response)
To use this with Flask, wrap the app object with the middleware: from flask import Flask app= Flask(__name__) app.wsgi_app= HTTPMethodOverrideMiddleware(app.wsgi_app)
152 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
1.21.24 Request Content Checksums
Various pieces of code can consume the request data and preprocess it. For instance JSON data ends up on the request object already read and processed, form data ends up there as well but goes through a different code path. This seems inconvenient when you want to calculate the checksum of the incoming request data. This is necessary sometimes for some APIs. Fortunately this is however very simple to change by wrapping the input stream. The following example calculates the SHA1 checksum of the incoming data as it gets read and stores it in the WSGI environment:
import hashlib
class ChecksumCalcStream(object):
def __init__(self, stream): self._stream= stream self._hash= hashlib.sha1()
def read(self, bytes): rv= self._stream.read(bytes) self._hash.update(rv) return rv
def readline(self, size_hint): rv= self._stream.readline(size_hint) self._hash.update(rv) return rv
def generate_checksum(request): env= request.environ stream= ChecksumCalcStream(env['wsgi.input']) env['wsgi.input']= stream return stream._hash
To use this, all you need to do is to hook the calculating stream in before the request starts consuming data. (Eg: be careful accessing request.form or anything of that nature. before_request_handlers for instance should be careful not to access it). Example usage:
@app.route('/special-api', methods=['POST']) def special_api(): hash= generate_checksum(request) # Accessing this parses the input stream files= request.files # At this point the hash is fully constructed. checksum= hash.hexdigest() return 'Hash was: %s'% checksum
1.21.25 Celery Background Tasks
If your application has a long running task, such as processing some uploaded data or sending email, you don’t want to wait for it to finish during a request. Instead, use a task queue to send the necessary data to another process that will run the task in the background while the request returns immediately.
1.21. Patterns for Flask 153 Flask Documentation (1.1.x), Release 1.1.4
Celery is a powerful task queue that can be used for simple background tasks as well as complex multi-stage programs and schedules. This guide will show you how to configure Celery using Flask, but assumes you’ve already read the First Steps with Celery guide in the Celery documentation.
Install
Celery is a separate Python package. Install it from PyPI using pip:
$ pip install celery
Configure
The first thing you need is a Celery instance, this is called the celery application. It serves the same purpose as the Flask object in Flask, just for Celery. Since this instance is used as the entry-point for everything you want to do in Celery, like creating tasks and managing workers, it must be possible for other modules to import it. For instance you can place this in a tasks module. While you can use Celery without any reconfiguration with Flask, it becomes a bit nicer by subclassing tasks and adding support for Flask’s application contexts and hooking it up with the Flask configuration. This is all that is necessary to properly integrate Celery with Flask: from celery import Celery def make_celery(app): celery= Celery( app.import_name, backend=app.config['CELERY_RESULT_BACKEND'], broker=app.config['CELERY_BROKER_URL'] ) celery.conf.update(app.config)
class ContextTask(celery.Task): def __call__(self, *args, **kwargs): with app.app_context(): return self.run(*args, **kwargs)
celery.Task= ContextTask return celery
The function creates a new Celery object, configures it with the broker from the application config, updates the rest of the Celery config from the Flask config and then creates a subclass of the task that wraps the task execution in an application context.
An example task
Let’s write a task that adds two numbers together and returns the result. We configure Celery’s broker and backend to use Redis, create a celery application using the factor from above, and then use it to define the task. from flask import Flask flask_app= Flask(__name__) flask_app.config.update( CELERY_BROKER_URL='redis://localhost:6379', (continues on next page)
154 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) CELERY_RESULT_BACKEND='redis://localhost:6379' ) celery= make_celery(flask_app)
@celery.task() def add_together(a, b): return a+b
This task can now be called in the background:
result= add_together.delay(23, 42) result.wait() # 65
Run a worker
If you jumped in and already executed the above code you will be disappointed to learn that .wait() will never actually return. That’s because you also need to run a Celery worker to receive and execute the task.
$ celery -A your_application.celery worker
The your_application string has to point to your application’s package or module that creates the celery object. Now that the worker is running, wait will return the result once the task is finished.
1.21.26 Subclassing Flask
The Flask class is designed for subclassing. For example, you may want to override how request parameters are handled to preserve their order:
from flask import Flask, Request from werkzeug.datastructures import ImmutableOrderedMultiDict class MyRequest(Request): """Request subclass to override request parameter storage""" parameter_storage_class= ImmutableOrderedMultiDict class MyFlask(Flask): """Flask subclass using the custom request class""" request_class= MyRequest
This is the recommended approach for overriding or augmenting Flask’s internal functionality.
1.21.27 Single-Page Applications
Flask can be used to serve Single-Page Applications (SPA) by placing static files produced by your frontend framework in a subfolder inside of your project. You will also need to create a catch-all endpoint that routes all requests to your SPA. The following example demonstrates how to serve an SPA along with an API:
from flask import Flask, jsonify
app= Flask(__name__, static_folder='app', static_url_path="/app") (continues on next page)
1.21. Patterns for Flask 155 Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page)
@app.route("/heartbeat") def heartbeat(): return jsonify({"status":"healthy"})
@app.route('/', defaults={'path':''}) @app.route('/
1.22 Deployment Options
While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well. Some of the options available for properly running Flask in production are documented here. If you want to deploy your Flask application to a WSGI server not listed here, look up the server documentation about how to use a WSGI app with it. Just remember that your Flask application object is the actual WSGI application.
1.22.1 Hosted options
• Deploying Flask on Heroku • Deploying Flask on Google App Engine • Deploying Flask on AWS Elastic Beanstalk • Deploying on Azure (IIS) • Deploying on PythonAnywhere
1.22.2 Self-hosted options
Standalone WSGI Containers
There are popular servers written in Python that contain WSGI applications and serve HTTP. These servers stand alone when they run; you can proxy to them from your web server. Note the section on Proxy Setups if you run into issues.
Gunicorn
Gunicorn ‘Green Unicorn’ is a WSGI HTTP Server for UNIX. It’s a pre-fork worker model ported from Ruby’s Unicorn project. It supports both eventlet and greenlet. Running a Flask application on this server is quite simple:
$ gunicorn myproject:app
Gunicorn provides many command-line options – see gunicorn -h. For example, to run a Flask application with 4 worker processes (-w 4) binding to localhost port 4000 (-b 127.0.0.1:4000):
$ gunicorn -w 4 -b 127.0.0.1:4000 myproject:app
156 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
The gunicorn command expects the names of your application module or package and the application instance within the module. If you use the application factory pattern, you can pass a call to that:
$ gunicorn "myproject:create_app()"
uWSGI
uWSGI is a fast application server written in C. It is very configurable which makes it more complicated to setup than gunicorn. Running uWSGI HTTP Router:
$ uwsgi --http 127.0.0.1:5000 --module myproject:app
For a more optimized setup, see configuring uWSGI and NGINX.
Gevent
Gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of libev event loop:
from gevent.pywsgi import WSGIServer from yourapplication import app
http_server= WSGIServer(('', 5000), app) http_server.serve_forever()
Twisted Web
Twisted Web is the web server shipped with Twisted, a mature, non-blocking event-driven networking library. Twisted Web comes with a standard WSGI container which can be controlled from the command line using the twistd utility:
$ twistd web --wsgi myproject.app
This example will run a Flask application called app from a module named myproject. Twisted Web supports many flags and options, and the twistd utility does as well; see twistd -h and twistd web -h for more information. For example, to run a Twisted Web server in the foreground, on port 8080, with an application from myproject:
$ twistd -n web --port tcp:8080 --wsgi myproject.app
Proxy Setups
If you deploy your application using one of these servers behind an HTTP proxy you will need to rewrite a few headers in order for the application to work. The two problematic values in the WSGI environment usually are REMOTE_ADDR and HTTP_HOST. You can configure your httpd to pass these headers, or you can fix them in middleware. Werkzeug ships a fixer that will solve some common setups, but you might want to write your own WSGI middleware for specific setups.
1.22. Deployment Options 157 Flask Documentation (1.1.x), Release 1.1.4
Here’s a simple nginx configuration which proxies to an application served on localhost at port 8000, setting appro- priate headers: server { listen 80;
server_name _;
access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log;
location /{ proxy_pass http://127.0.0.1:8000/; proxy_redirect off;
proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
If your httpd is not providing these headers, the most common setup invokes the host being set from X-Forwarded-Host and the remote address from X-Forwarded-For: from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app= ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
Trusting Headers Please keep in mind that it is a security issue to use such a middleware in a non-proxy setup because it will blindly trust the incoming headers which might be forged by malicious clients.
If you want to rewrite the headers from another header, you might want to use a fixer like this: class CustomProxyFix(object):
def __init__(self, app): self.app= app
def __call__(self, environ, start_response): host= environ.get('HTTP_X_FHOST','') if host: environ['HTTP_HOST']= host return self.app(environ, start_response) app.wsgi_app= CustomProxyFix(app.wsgi_app) uWSGI uWSGI is a deployment option on servers like nginx, lighttpd, and cherokee; see FastCGI and Standalone WSGI Containers for other options. To use your WSGI application with uWSGI protocol you will need a uWSGI server first. uWSGI is both a protocol and an application server; the application server can serve uWSGI, FastCGI, and HTTP protocols.
158 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
The most popular uWSGI server is uwsgi, which we will use for this guide. Make sure to have it installed to follow along.
Watch Out Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ == '__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to uWSGI.
Starting your app with uwsgi
uwsgi is designed to operate on WSGI callables found in python modules. Given a flask application in myapp.py, use the following command:
$ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /
˓→yourapplication=myapp:app
The --manage-script-name will move the handling of SCRIPT_NAME to uwsgi, since it is smarter about that. It is used together with the --mount directive which will make requests to /yourapplication be directed to myapp:app. If your application is accessible at root level, you can use a single / instead of /yourapplication. myapp refers to the name of the file of your flask application (without extension) or the module which provides app. app is the callable inside of your application (usually the line reads app = Flask(__name__). If you want to deploy your flask application inside of a virtual environment, you need to also add --virtualenv /path/to/virtual/environment. You might also need to add --plugin python or --plugin python3 depending on which python version you use for your project.
Configuring nginx
A basic flask nginx configuration looks like this:
location = /yourapplication { rewrite ^ /yourapplication/; } location /yourapplication { try_files $uri @yourapplication; } location @yourapplication { include uwsgi_params; uwsgi_pass unix:/tmp/yourapplication.sock; }
This configuration binds the application to /yourapplication. If you want to have it in the URL root its a bit simpler:
location / { try_files $uri @yourapplication; } location @yourapplication { include uwsgi_params; uwsgi_pass unix:/tmp/yourapplication.sock; }
mod_wsgi (Apache)
If you are using the Apache webserver, consider using mod_wsgi.
1.22. Deployment Options 159 Flask Documentation (1.1.x), Release 1.1.4
Watch Out Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ == '__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to mod_wsgi.
Installing mod_wsgi
If you don’t have mod_wsgi installed yet you have to either install it using a package manager or compile it yourself. The mod_wsgi installation instructions cover source installations on UNIX systems. If you are using Ubuntu/Debian you can apt-get it and activate it as follows:
$ apt-get install libapache2-mod-wsgi-py3
If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you can install it as follows:
$ yum install mod_wsgi
On FreeBSD install mod_wsgi by compiling the www/mod_wsgi port or by using pkg_add:
$ pkg install ap24-py37-mod_wsgi
If you are using pkgsrc you can install mod_wsgi by compiling the www/ap2-wsgi package. If you encounter segfaulting child processes after the first apache reload you can safely ignore them. Just restart the server.
Creating a .wsgi file
To run your application you need a yourapplication.wsgi file. This file contains the code mod_wsgi is execut- ing on startup to get the application object. The object called application in that file is then used as application. For most applications the following file should be sufficient:
from yourapplication import app as application
If a factory function is used in a __init__.py file, then the function should be imported:
from yourapplication import create_app application= create_app()
If you don’t have a factory function for application creation but a singleton instance you can directly import that one as application. Store that file somewhere that you will find it again (e.g.: /var/www/yourapplication) and make sure that yourapplication and all the libraries that are in use are on the python load path. If you don’t want to install it system wide consider using a virtual python instance. Keep in mind that you will have to actually install your application into the virtualenv as well. Alternatively there is the option to just patch the path in the .wsgi file before the import:
import sys sys.path.insert(0,'/path/to/the/application')
160 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Configuring Apache
The last thing you have to do is to create an Apache configuration file for your application. In this example we are telling mod_wsgi to execute the application under a different user for security reasons:
WSGIDaemonProcess yourapplication user=user1 group=group1 threads=5 WSGIScriptAlias/ /var/www/yourapplication/yourapplication.wsgi
Note: WSGIDaemonProcess isn’t implemented in Windows and Apache will refuse to run with the above configura- tion. On a Windows system, eliminate those lines:
Note: There have been some changes in access control configuration for Apache 2.4. Most notably, the syntax for directory permissions has changed from httpd 2.2
Order allow,deny Allow from all to httpd 2.4 syntax
Require all granted
For more information consult the mod_wsgi documentation.
Troubleshooting
If your application does not run, follow this guide to troubleshoot: Problem: application does not run, errorlog shows SystemExit ignored You have an app.run() call in your application file that is not guarded by an if __name__ == '__main__': condition. Either remove that run() call from the file and move it into a separate run.py file or put it into such an if block. Problem: application gives permission errors Probably caused by your application running as the wrong user. Make sure the folders the application needs access to have the proper privileges set and the application runs as the correct user (user and group parameter to the WSGIDaemonProcess directive)
1.22. Deployment Options 161 Flask Documentation (1.1.x), Release 1.1.4
Problem: application dies with an error on print Keep in mind that mod_wsgi disallows doing anything with sys.stdout and sys.stderr. You can disable this protection from the config by setting the WSGIRe- strictStdout to off:
WSGIRestrictStdout Off
Alternatively you can also replace the standard out in the .wsgi file with a different stream:
import sys sys.stdout= sys.stderr
Problem: accessing resources gives IO errors Your application probably is a single .py file you symlinked into the site-packages folder. Please be aware that this does not work, instead you either have to put the folder into the pythonpath the file is stored in, or convert your application into a package. The reason for this is that for non-installed packages, the module filename is used to locate the resources and for symlinks the wrong filename is picked up.
Support for Automatic Reloading
To help deployment tools you can activate support for automatic reloading. Whenever something changes the .wsgi file, mod_wsgi will reload all the daemon processes for us. For that, just add the following directive to your Directory section:
WSGIScriptReloading On
Working with Virtual Environments
Virtual environments have the advantage that they never install the required dependencies system wide so you have a better control over what is used where. If you want to use a virtual environment with mod_wsgi you have to modify your .wsgi file slightly. Add the following lines to the top of your .wsgi file:
activate_this='/path/to/env/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this))
For Python 3 add the following lines to the top of your .wsgi file:
activate_this='/path/to/env/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this))
This sets up the load paths according to the settings of the virtual environment. Keep in mind that the path has to be absolute.
FastCGI
FastCGI is a deployment option on servers like nginx, lighttpd, and cherokee; see uWSGI and Standalone WSGI Containers for other options. To use your WSGI application with any of them you will need a FastCGI server first. The most popular one is flup which we will use for this guide. Make sure to have it installed to follow along.
Watch Out
162 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ == '__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to FastCGI.
Creating a .fcgi file
First you need to create the FastCGI server file. Let’s call it yourapplication.fcgi:
#!/usr/bin/python from flup.server.fcgi import WSGIServer from yourapplication import app
if __name__ =='__main__': WSGIServer(app).run()
This is enough for Apache to work, however nginx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work you need to pass the path to the socket to the WSGIServer:
WSGIServer(application, bindAddress='/path/to/fcgi.sock').run()
The path has to be the exact same path you define in the server config. Save the yourapplication.fcgi file somewhere you will find it again. It makes sense to have that in /var/ www/yourapplication or something similar. Make sure to set the executable bit on that file so that the servers can execute it:
$ chmod +x /var/www/yourapplication/yourapplication.fcgi
Configuring Apache
The example above is good enough for a basic Apache deployment but your .fcgi file will appear in your application URL e.g. example.com/yourapplication.fcgi/news/. There are few ways to configure your application so that yourapplication.fcgi does not appear in the URL. A preferable way is to use the ScriptAlias and SetHandler configuration directives to route requests to the FastCGI server. The following example uses FastCgiServer to start 5 instances of the application which will handle all incoming requests:
LoadModule fastcgi_module/usr/lib64/httpd/modules/mod_fastcgi.so
FastCgiServer/var/www/html/yourapplication/app.fcgi-idle-timeout 300-processes5
AddHandler fastcgi-script fcgi ScriptAlias//var/www/html/yourapplication/app.fcgi/
1.22. Deployment Options 163 Flask Documentation (1.1.x), Release 1.1.4
These processes will be managed by Apache. If you’re using a standalone FastCGI server, you can use the FastCgiEx- ternalServer directive instead. Note that in the following the path is not real, it’s simply used as an identifier to other directives such as AliasMatch:
FastCgiServer/var/www/html/yourapplication-host 127.0.0.1:3000
If you cannot set ScriptAlias, for example on a shared web host, you can use WSGI middleware to remove yourappli- cation.fcgi from the URLs. Set .htaccess:
Set yourapplication.fcgi:
#!/usr/bin/python #: optional path to your local python site-packages folder import sys sys.path.insert(0,'
def __call__(self, environ, start_response): environ['SCRIPT_NAME']='' return self.app(environ, start_response) app= ScriptNameStripper(app) if __name__ =='__main__': WSGIServer(app).run()
Configuring lighttpd
A basic FastCGI configuration for lighttpd looks like that: fastcgi.server=("/yourapplication.fcgi"=> (( "socket"=>"/tmp/yourapplication-fcgi.sock", "bin-path"=>"/var/www/yourapplication/yourapplication.fcgi", (continues on next page)
164 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
(continued from previous page) "check-local"=>"disable", "max-procs"=>1 )) )
alias.url=( "/static/"=>"/path/to/your/static/" )
url.rewrite-once=( "^(/static($|/.*))$"=>"$1", "^(/.*)$"=>"/yourapplication.fcgi$1" )
Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to / yourapplication. If you want the application to work in the URL root you have to work around a lighttpd bug with the LighttpdCGIRootFix middleware. Make sure to apply it only if you are mounting the application the URL root. Also, see the Lighty docs for more information on FastCGI and Python (note that explicitly passing a socket to run() is no longer necessary).
Configuring nginx
Installing FastCGI applications on nginx is a bit different because by default no FastCGI parameters are forwarded. A basic Flask FastCGI configuration for nginx looks like this:
location = /yourapplication { rewrite ^ /yourapplication/ last; } location /yourapplication { try_files $uri @yourapplication; } location @yourapplication { include fastcgi_params; fastcgi_split_path_info ^(/yourapplication)(.*)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; }
This configuration binds the application to /yourapplication. If you want to have it in the URL root it’s a bit simpler because you don’t have to figure out how to calculate PATH_INFO and SCRIPT_NAME:
location / { try_files $uri @yourapplication; } location @yourapplication { include fastcgi_params; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param SCRIPT_NAME ""; fastcgi_pass unix:/tmp/yourapplication-fcgi.sock; }
Running FastCGI Processes
Since nginx and others do not load FastCGI apps, you have to do it by yourself. Supervisor can manage FastCGI processes. You can look around for other FastCGI process managers or write a script to run your .fcgi file at boot, e.g. using a SysV init.d script. For a temporary solution, you can always run the .fcgi script inside GNU screen. See man screen for details, and note that this is a manual solution which does not persist across system restart:
1.22. Deployment Options 165 Flask Documentation (1.1.x), Release 1.1.4
$ screen $ /var/www/yourapplication/yourapplication.fcgi
Debugging
FastCGI deployments tend to be hard to debug on most web servers. Very often the only thing the server log tells you is something along the lines of “premature end of headers”. In order to debug the application the only thing that can really give you ideas why it breaks is switching to the correct user and executing the application by hand. This example assumes your application is called application.fcgi and that your web server user is www-data:
$ su www-data $ cd /var/www/yourapplication $ python application.fcgi Traceback (most recent call last): File "yourapplication.fcgi", line 4, in
In this case the error seems to be “yourapplication” not being on the python path. Common problems are: • Relative paths being used. Don’t rely on the current working directory. • The code depending on environment variables that are not set by the web server. • Different python interpreters being used.
CGI
If all other deployment methods do not work, CGI will work for sure. CGI is supported by all major servers but usually has a sub-optimal performance. This is also the way you can use a Flask application on Google’s App Engine, where execution happens in a CGI-like environment.
Watch Out Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ == '__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to CGI / app engine. With CGI, you will also have to make sure that your code does not contain any print statements, or that sys. stdout is overridden by something that doesn’t write into the HTTP response.
Creating a .cgi file
First you need to create the CGI application file. Let’s call it yourapplication.cgi:
#!/usr/bin/python from wsgiref.handlers import CGIHandler from yourapplication import app
CGIHandler().run(app)
166 Chapter 1. User’s Guide Flask Documentation (1.1.x), Release 1.1.4
Server Setup
Usually there are two ways to configure the server. Either just copy the .cgi into a cgi-bin (and use mod_rewrite or something similar to rewrite the URL) or let the server point to the file directly. In Apache for example you can put something like this into the config:
ScriptAlias /app /path/to/the/application.cgi
On shared webhosting, though, you might not have access to your Apache config. In this case, a file called . htaccess, sitting in the public directory you want your app to be available, works too but the ScriptAlias directive won’t work in that case:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]
For more information consult the documentation of your webserver.
1.23 Becoming Big
Here are your options when growing your codebase or scaling your application.
1.23.1 Read the Source.
Flask started in part to demonstrate how to build your own framework on top of existing well-used tools Werkzeug (WSGI) and Jinja (templating), and as it developed, it became useful to a wide audience. As you grow your codebase, don’t just use Flask – understand it. Read the source. Flask’s code is written to be read; its documentation is published so you can use its internal APIs. Flask sticks to documented APIs in upstream libraries, and documents its internal utilities so that you can find the hook points needed for your project.
1.23.2 Hook. Extend.
The API docs are full of available overrides, hook points, and Signals. You can provide custom classes for things like the request and response objects. Dig deeper on the APIs you use, and look for the customizations which are available out of the box in a Flask release. Look for ways in which your project can be refactored into a collection of utilities and Flask extensions. Explore the many Extensions in the community, and look for patterns to build your own extensions if you do not find the tools you need.
1.23.3 Subclass.
The Flask class has many methods designed for subclassing. You can quickly add or customize behavior by sub- classing Flask (see the linked method docs) and using that subclass wherever you instantiate an application class. This works well with Application Factories. See Subclassing Flask for an example.
1.23.4 Wrap with middleware.
The Application Dispatching chapter shows in detail how to apply middleware. You can introduce WSGI middleware to wrap your Flask instances and introduce fixes and changes at the layer between your Flask application and your HTTP server. Werkzeug includes several middlewares.
1.23. Becoming Big 167 Flask Documentation (1.1.x), Release 1.1.4
1.23.5 Fork.
If none of the above options work, fork Flask. The majority of code of Flask is within Werkzeug and Jinja2. These libraries do the majority of the work. Flask is just the paste that glues those together. For every project there is the point where the underlying framework gets in the way (due to assumptions the original developers had). This is natural because if this would not be the case, the framework would be a very complex system to begin with which causes a steep learning curve and a lot of user frustration. This is not unique to Flask. Many people use patched and modified versions of their framework to counter shortcom- ings. This idea is also reflected in the license of Flask. You don’t have to contribute any changes back if you decide to modify the framework. The downside of forking is of course that Flask extensions will most likely break because the new framework has a different import name. Furthermore integrating upstream changes can be a complex process, depending on the number of changes. Because of that, forking should be the very last resort.
1.23.6 Scale like a pro.
For many web applications the complexity of the code is less an issue than the scaling for the number of users or data entries expected. Flask by itself is only limited in terms of scaling by your application code, the data store you want to use and the Python implementation and webserver you are running on. Scaling well means for example that if you double the amount of servers you get about twice the performance. Scaling bad means that if you add a new server the application won’t perform any better or would not even support a second server. There is only one limiting factor regarding scaling in Flask which are the context local proxies. They depend on context which in Flask is defined as being either a thread, process or greenlet. If your server uses some kind of concurrency that is not based on threads or greenlets, Flask will no longer be able to support these global proxies. However the majority of servers are using either threads, greenlets or separate processes to achieve concurrency which are all methods well supported by the underlying Werkzeug library.
1.23.7 Discuss with the community.
The Flask developers keep the framework accessible to users with codebases big and small. If you find an obstacle in your way, caused by Flask, don’t hesitate to contact the developers on the mailing list or Discord server. The best way for the Flask and Flask extension developers to improve the tools for larger applications is getting feedback from users.
168 Chapter 1. User’s Guide CHAPTER TWO
API REFERENCE
If you are looking for information on a specific function, class or method, this part of the documentation is for you.
2.1 API
This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation.
2.1.1 Application Object class flask.Flask(import_name, static_url_path=None, static_folder=’static’, static_host=None, host_matching=False, subdomain_matching=False, template_folder=’templates’, instance_path=None, instance_relative_config=False, root_path=None) The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an __init__.py file inside) or a standard module (just a .py file). For more information about resource loading, see open_resource(). Usually you create a Flask instance in your main module or in the __init__.py file of your package like this:
from flask import Flask app= Flask(__name__)
About the First Parameter The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more. So it’s important what you provide there. If you are using a single module, __name__ is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there. For example if your application is defined in yourapplication/app.py you should create it with one of the two versions below:
169 Flask Documentation (1.1.x), Release 1.1.4
app= Flask('yourapplication') app= Flask(__name__.split('.')[0])
Why is that? The application will work even with __name__, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that trig- gered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in yourapplication.app and not yourapplication.views.frontend)
New in version 1.0: The host_matching and static_host parameters were added. New in version 1.0: The subdomain_matching parameter was added. Subdomain matching needs to be enabled manually now. Setting SERVER_NAME does not implicitly enable it. New in version 0.11: The root_path parameter was added. New in version 0.8: The instance_path and instance_relative_config parameters were added. New in version 0.7: The static_url_path, static_folder, and template_folder parameters were added. Parameters • import_name – the name of the application package • static_url_path – can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder. • static_folder – The folder with static files that is served at static_url_path. Relative to the application root_path or an absolute path. Defaults to 'static'. • static_host – the host to use when adding the static route. Defaults to None. Required when using host_matching=True with a static_folder configured. • host_matching – set url_map.host_matching attribute. Defaults to False. • subdomain_matching – consider the subdomain relative to SERVER_NAME when matching routes. Defaults to False. • template_folder – the folder that contains the templates that should be used by the application. Defaults to 'templates' folder in the root path of the application. • instance_path – An alternative instance path for the application. By default the folder 'instance' next to the package or module is assumed to be the instance path. • instance_relative_config – if set to True relative filenames for loading the con- fig are assumed to be relative to the instance path instead of the application root. • root_path – Flask by default will automatically calculate the path to the root of the application. In certain situations this cannot be achieved (for instance if the package is a Python 3 namespace package) and needs to be manually defined. add_template_filter(f, name=None) Register a custom template filter. Works exactly like the template_filter() decorator. Parameters name – the optional name of the filter, otherwise the function name will be used. add_template_global(f, name=None) Register a custom template global function. Works exactly like the template_global() decorator. New in version 0.10. Parameters name – the optional name of the global function, otherwise the function name will be used.
170 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
add_template_test(f, name=None) Register a custom template test. Works exactly like the template_test() decorator. New in version 0.10. Parameters name – the optional name of the test, otherwise the function name will be used. add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **op- tions) Connects a URL rule. Works exactly like the route() decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:
@app.route('/') def index(): pass
Is equivalent to the following:
def index(): pass app.add_url_rule('/','index', index)
If the view_func is not provided you will need to connect the endpoint to a view function like so:
app.view_functions['index']= index
Internally route() invokes add_url_rule() so if you want to customize the behavior via subclass- ing you only need to change this method. For more information refer to URL Route Registrations. Changed in version 0.6: OPTIONS is added automatically as method. Changed in version 0.2: view_func parameter added. Parameters • rule – the URL rule as string • endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint • view_func – the function to call when serving a request to the provided endpoint • provide_automatic_options – controls whether the OPTIONS method should be added automatically. This can also be controlled by setting the view_func. provide_automatic_options = False before adding the rule. • options – the options to be forwarded to the underlying Rule object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD). Starting with Flask 0.6, OPTIONS is implicitly added and handled by the standard request handling. after_request(f ) Register a function to be run after each request. Your function must take one parameter, an instance of response_class and return a new response object or the same (see process_response()).
2.1. API 171 Flask Documentation (1.1.x), Release 1.1.4
As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred. after_request_funcs = None A dictionary with lists of functions that should be called after each request. The key of the dictionary is the name of the blueprint this function is active for, None for all requests. This can for example be used to close database connections. To register a function here, use the after_request() decorator. app_context() Create an AppContext. Use as a with block to push the context, which will make current_app point at this application. An application context is automatically pushed by RequestContext.push() when handling a re- quest, and when running a CLI command. Use this to manually create a context outside of these situations.
with app.app_context(): init_db()
See The Application Context. New in version 0.9. app_ctx_globals_class alias of flask.ctx._AppCtxGlobals auto_find_instance_path() Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named instance next to your main file or the package. New in version 0.8. before_first_request(f ) Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. New in version 0.8. before_first_request_funcs = None A list of functions that will be called at the beginning of the first request to this instance. To register a function, use the before_first_request() decorator. New in version 0.8. before_request(f ) Registers a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. before_request_funcs = None A dictionary with lists of functions that will be called at the beginning of each request. The key of the dictionary is the name of the blueprint this function is active for, or None for all requests. To register a function, use the before_request() decorator. blueprints = None all the attached blueprints in a dictionary by name. Blueprints can be attached multiple times so this dictionary does not tell you how often they got attached. New in version 0.7.
172 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
config = None The configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files. config_class alias of flask.config.Config context_processor(f ) Registers a template context processor function. create_global_jinja_loader() Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It’s discouraged to override this function. Instead one should override the jinja_loader() function instead. The global loader dispatches between the loaders of the application and the individual blueprints. New in version 0.7. create_jinja_environment() Create the Jinja environment based on jinja_options and the various Jinja-related methods of the app. Changing jinja_options after this will have no effect. Also adds Flask-related globals and filters to the environment. Changed in version 0.11: Environment.auto_reload set in accordance with TEMPLATES_AUTO_RELOAD configuration option. New in version 0.5. create_url_adapter(request) Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomain matching. Use subdomain_matching instead. Changed in version 0.9: This can now also be called without a request object when the URL adapter is created for the application context. New in version 0.6. property debug Whether debug mode is enabled. When using flask run to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. This maps to the DEBUG config key. This is enabled when env is 'development' and is overridden by the FLASK_DEBUG environment variable. It may not behave as expected if set in code. Do not enable debug mode when deploying in production. Default: True if env is 'development', or False otherwise. default_config = {'APPLICATION_ROOT': '/', 'DEBUG': None, 'ENV': None, 'EXPLAIN_TEMPLATE_LOADING': False, 'JSONIFY_MIMETYPE': 'application/json', 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'MAX_CONTENT_LENGTH': None, 'MAX_COOKIE_SIZE': 4093, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'PREFERRED_URL_SCHEME': 'http', 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'SERVER_NAME': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'TEMPLATES_AUTO_RELOAD': None, 'TESTING': False, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'USE_X_SENDFILE': False} Default configuration parameters. dispatch_request() Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call make_response(). Changed in version 0.7: This no longer does the exception handling, this code was moved to the new full_dispatch_request().
2.1. API 173 Flask Documentation (1.1.x), Release 1.1.4
do_teardown_appcontext(exc=
@app.endpoint('example.endpoint') def example(): return "example"
Parameters endpoint – the name of the endpoint
env What environment the app is running in. Flask and extensions may enable behaviors based on the envi- ronment, such as enabling debug mode. This maps to the ENV config key. This is set by the FLASK_ENV environment variable and may not behave as expected if set in code. Do not enable development when deploying in production. Default: 'production' error_handler_spec = None A dictionary of all registered error handlers. The key is None for error handlers active on the application, otherwise the key is the name of the blueprint. Each key points to another dictionary where the key is the status code of the http exception. The special key None points to a list of tuples where the first item is the class for the instance check and the second the error handler function. To register an error handler, use the errorhandler() decorator. errorhandler(code_or_exception) Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:
174 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
@app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500
New in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, for application wide error handlers. New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class. Parameters code_or_exception – the code as integer for the handler, or an arbitrary ex- ception extensions = None a place where extensions can store application specific state. For example this is where an extension could store database engines and similar things. For backwards compatibility extensions should register themselves like this:
if not hasattr(app,'extensions'): app.extensions={} app.extensions['extensionname']= SomeObject()
The key must match the name of the extension module. For example in case of a “Flask-Foo” extension in flask_foo, the key would be 'foo'. New in version 0.7. finalize_request(rv, from_error_handler=False) Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers. Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the from_error_handler flag. If enabled, failures in response processing will be logged and otherwise ignored. Internal full_dispatch_request() Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP excep- tion catching and error handling. New in version 0.7. get_send_file_max_age(filename) Provides default cache_timeout for the send_file() functions. By default, this function returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. Static file functions such as send_from_directory() use this function, and send_file() calls this function on current_app when the given cache_timeout is None. If a cache_timeout is given in send_file(), that timeout is used; otherwise, this method is called.
2.1. API 175 Flask Documentation (1.1.x), Release 1.1.4
This allows subclasses to change the behavior when sending files based on the filename. For example, to set the cache timeout for .js files to 60 seconds:
class MyFlask(flask.Flask): def get_send_file_max_age(self, name): if name.lower().endswith('.js'): return 60 return flask.Flask.get_send_file_max_age(self, name)
New in version 0.9. property got_first_request This attribute is set to True if the application started handling the first request. New in version 0.8. handle_exception(e) Handle an exception that did not have an error handler associated with it, or that was raised from an error handler. This always causes a 500 InternalServerError. Always sends the got_request_exception signal. If propagate_exceptions is True, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an InternalServerError is returned. If an error handler is registered for InternalServerError or 500, it will be used. For consistency, the handler will always receive the InternalServerError. The original unhandled exception is available as e.original_exception.
Note: Prior to Werkzeug 1.0.0, InternalServerError will not always have an original_exception attribute. Use getattr(e, "original_exception", None) to simulate the behavior for compatibility.
Changed in version 1.1.0: Always passes the InternalServerError instance to the handler, setting original_exception to the unhandled error. Changed in version 1.1.0: after_request functions and other finalization is done even for the default 500 response when there is no handler. New in version 0.3. handle_http_exception(e) Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. Changed in version 1.0.3: RoutingException, used internally for actions such as slash redirects dur- ing routing, is not passed to error handlers. Changed in version 1.0: Exceptions are looked up by code and by MRO, so HTTPExcpetion subclasses can be handled with a catch-all handler for the base HTTPException. New in version 0.3. handle_url_build_error(error, endpoint, values) Handle BuildError on url_for(). handle_user_exception(e) This method is called whenever an exception occurs that should be handled. A special case is HTTPException which is forwarded to the handle_http_exception() method. This function will either return a response value or reraise the exception with the same traceback.
176 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
Changed in version 1.0: Key errors raised from request data like form show the bad key in debug mode rather than a generic bad request message. New in version 0.7. property has_static_folder This is True if the package bound object’s container has a folder for static files. New in version 0.5. import_name = None The name of the package or module that this app belongs to. Do not change this once it is set by the constructor. inject_url_defaults(endpoint, values) Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. New in version 0.7. instance_path = None Holds the path to the instance folder. New in version 0.8. iter_blueprints() Iterates over all blueprints by the order they were registered. New in version 0.11. jinja_env The Jinja environment used to load templates. The environment is created the first time this property is accessed. Changing jinja_options after that will have no effect. jinja_environment alias of flask.templating.Environment jinja_loader The Jinja loader for this package bound object. New in version 0.5. jinja_options = {'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_']} Options that are passed to the Jinja environment in create_jinja_environment(). Changing these options after the environment is created (accessing jinja_env) will have no effect. Changed in version 1.1.0: This is a dict instead of an ImmutableDict to allow easier configuration. json_decoder alias of flask.json.JSONDecoder json_encoder alias of flask.json.JSONEncoder log_exception(exc_info) Logs an exception. This is called by handle_exception() if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the logger. New in version 0.8. logger A standard Python Logger for the app, with the same name as name.
2.1. API 177 Flask Documentation (1.1.x), Release 1.1.4
In debug mode, the logger’s level will be set to DEBUG. If there are no handlers configured, a default handler will be added. See Logging for more information. Changed in version 1.1.0: The logger takes the same name as name rather than hard-coding "flask. app". Changed in version 1.0.0: Behavior was simplified. The logger is always named "flask.app". The level is only set during configuration, it doesn’t check app.debug each time. Only one format is used, not different ones depending on app.debug. No handlers are removed, and a handler is only added if no handlers are already configured. New in version 0.3. make_config(instance_relative=False) Used to create the config attribute by the Flask constructor. The instance_relative parameter is passed in from the constructor of Flask (there named instance_relative_config) and indicates if the config should be relative to the instance path or the root path of the application. New in version 0.8. make_default_options_response() This method is called to create the default OPTIONS response. This can be changed through subclassing to change the default behavior of OPTIONS responses. New in version 0.7. make_null_session() Creates a new instance of a missing session. Instead of overriding this method we recommend replacing the session_interface. New in version 0.7. make_response(rv) Convert the return value from a view function to an instance of response_class. Parameters rv – the return value from the view function. The view function must return a re- sponse. Returning None, or the view ending without returning, is not allowed. The following types are allowed for view_rv: str (unicode in Python 2) A response object is created with the string encoded to UTF-8 as the body. bytes (str in Python 2) A response object is created with the bytes as the body. dict A dictionary that will be jsonify’d before being returned. tuple Either (body, status, headers), (body, status), or (body, headers), where body is any of the other types allowed here, status is a string or an integer, and headers is a dictionary or a list of (key, value) tuples. If body is a response_class instance, status overwrites the exiting value and headers are extended. response_class The object is returned unchanged. other Response class The object is coerced to response_class. callable() The function is called as a WSGI application. The result is used to create a response object. Changed in version 0.9: Previously a tuple was interpreted as the arguments for the response object.
178 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
make_shell_context() Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors. New in version 0.11. name The name of the application. This is usually the import name with the difference that it’s guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value. New in version 0.8. open_instance_resource(resource, mode=’rb’) Opens a resource from the application’s instance folder (instance_path). Otherwise works like open_resource(). Instance resources can also be opened for writing. Parameters • resource – the name of the resource. To access resources within subfolders use forward slashes as separator. • mode – resource file opening mode, default is ‘rb’. open_resource(resource, mode=’rb’) Opens a resource from the application’s resource folder. To see how this works, consider the following folder structure:
/myapplication.py /schema.sql /static /style.css /templates /layout.html /index.html
If you want to open the schema.sql file you would do the following:
with app.open_resource('schema.sql') as f: contents=f.read() do_something_with(contents)
Parameters • resource – the name of the resource. To access resources within subfolders use forward slashes as separator. • mode – Open file in this mode. Only reading is supported, valid values are “r” (or “rt”) and “rb”.
open_session(request) Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the secret_key is set. Instead of overriding this method we recommend replacing the session_interface. Parameters request – an instance of request_class. permanent_session_lifetime A timedelta which is used to set the expiration date of a permanent session. The default is 31 days which makes a permanent session survive for roughly one month.
2.1. API 179 Flask Documentation (1.1.x), Release 1.1.4
This attribute can also be configured from the config with the PERMANENT_SESSION_LIFETIME con- figuration key. Defaults to timedelta(days=31) preprocess_request() Called before the request is dispatched. Calls url_value_preprocessors registered with the app and the current blueprint (if any). Then calls before_request_funcs registered with the app and the blueprint. If any before_request() handler returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. property preserve_context_on_exception Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION configuration value in case it’s set, otherwise a sensible default is returned. New in version 0.7. process_response(response) Can be overridden in order to modify the response object before it’s sent to the WSGI server. By default this will call all the after_request() decorated functions. Changed in version 0.5: As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration. Parameters response – a response_class object. Returns a new response object or the same, has to be an instance of response_class. property propagate_exceptions Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it’s set, otherwise a sensible default is returned. New in version 0.7. raise_routing_exception(request) Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non GET, HEAD, or OPTIONS requests and we’re raising a different error instead to help debug situations. Internal register_blueprint(blueprint, **options) Register a Blueprint on the application. Keyword arguments passed to this method will override the defaults set on the blueprint. Calls the blueprint’s register() method after recording the blueprint in the application’s blueprints. Parameters • blueprint – The blueprint to register. • url_prefix – Blueprint routes will be prefixed with this. • subdomain – Blueprint routes will match on this subdomain. • url_defaults – Blueprint routes will use these default values for view arguments. • options – Additional keyword arguments are passed to BlueprintSetupState. They can be accessed in record() callbacks. New in version 0.7.
180 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
register_error_handler(code_or_exception, f ) Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage. New in version 0.7. request_class alias of flask.wrappers.Request request_context(environ) Create a RequestContext representing a WSGI environment. Use a with block to push the context, which will make request point at this request. See The Request Context. Typically you should not call this from your own code. A request context is automatically pushed by the wsgi_app() when handling a request. Use test_request_context() to create an environment and context instead of this method. Parameters environ – a WSGI environment response_class alias of flask.wrappers.Response root_path = None Absolute path to the package on the filesystem. Used to look up resources contained in the package. route(rule, **options) A decorator that is used to register a view function for a given URL rule. This does the same thing as add_url_rule() but is intended for decorator usage:
@app.route('/') def index(): return 'Hello World'
For more information refer to URL Route Registrations. Parameters • rule – the URL rule as string • endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint • options – the options to be forwarded to the underlying Rule object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD). Starting with Flask 0.6, OPTIONS is implicitly added and handled by the standard request handling. run(host=None, port=None, debug=None, load_dotenv=True, **options) Runs the application on a local development server. Do not use run() in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see Deployment Options for WSGI server recommendations. If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debug- ger, you can pass use_evalex=False as parameter. This will keep the debugger’s traceback screen active, but disable code execution.
2.1. API 181 Flask Documentation (1.1.x), Release 1.1.4
It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the flask command line script’s run support.
Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke run() with debug=True and use_reloader=False. Setting use_debugger to True without being in debug mode won’t catch any exceptions because there won’t be any to catch.
Parameters • host – the hostname to listen on. Set this to '0.0.0.0' to have the server available externally as well. Defaults to '127.0.0.1' or the host in the SERVER_NAME config variable if present. • port – the port of the webserver. Defaults to 5000 or the port defined in the SERVER_NAME config variable if present. • debug – if given, enable or disable debug mode. See debug. • load_dotenv – Load the nearest .env and .flaskenv files to set environment vari- ables. Will also change the working directory to the directory containing the first file found. • options – the options to be forwarded to the underlying Werkzeug server. See werkzeug.serving.run_simple() for more information.
Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files. If set, the FLASK_ENV and FLASK_DEBUG environment variables will override env and debug. Threaded mode is enabled by default. Changed in version 0.10: The default port is now picked from the SERVER_NAME variable. save_session(session, response) Saves the session if it needs updates. For the default implementation, check open_session(). Instead of overriding this method we recommend replacing the session_interface. Parameters • session – the session to be saved (a SecureCookie object) • response – an instance of response_class secret_key If a secret key is set, cryptographic components can use this to sign cookies and other things. Set this to a complex random value when you want to use the secure cookie for instance. This attribute can also be configured from the config with the SECRET_KEY configuration key. Defaults to None. select_jinja_autoescape(filename) Returns True if autoescaping should be active for the given template name. If no template name is given, returns True. New in version 0.5.
182 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
send_file_max_age_default A timedelta which is used as default cache_timeout for the send_file() functions. The default is 12 hours. This attribute can also be configured from the config with the SEND_FILE_MAX_AGE_DEFAULT con- figuration key. This configuration variable can also be set with an integer value used as seconds. Defaults to timedelta(hours=12) send_static_file(filename) Function used internally to send static files from the static folder to the browser. New in version 0.5. session_cookie_name The secure cookie uses this for the name of the session cookie. This attribute can also be configured from the config with the SESSION_COOKIE_NAME configuration key. Defaults to 'session' session_interface =
ctx= app.app_context() ctx.push() ... ctx.pop()
When ctx.pop() is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.
2.1. API 183 Flask Documentation (1.1.x), Release 1.1.4
Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an unhandled exception it will be passed an error object. If an errorhandler() is registered, it will handle the exception and the teardown will not receive it. The return values of teardown functions are ignored. New in version 0.9. teardown_appcontext_funcs = None A list of functions that are called when the application context is destroyed. Since the application context is also torn down if the request ends this is the place to store code that disconnects from databases. New in version 0.9. teardown_request(f ) Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed. Example:
ctx= app.test_request_context() ctx.push() ... ctx.pop()
When ctx.pop() is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored.
Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.
teardown_request_funcs = None A dictionary with lists of functions that are called after each request, even if an exception has occurred. The key of the dictionary is the name of the blueprint this function is active for, None for all requests. These functions are not allowed to modify the request, and their return values are ignored. If an exception occurred while processing the request, it gets passed to each teardown_request function. To register a function here, use the teardown_request() decorator. New in version 0.7. template_context_processors = None A dictionary with list of functions that are called without argument to populate the template context. The key of the dictionary is the name of the blueprint this function is active for, None for all requests. Each returns a dictionary that the template context is updated with. To register a function here, use the context_processor() decorator.
184 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
template_filter(name=None) A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:
@app.template_filter() def reverse(s): return s[::-1]
Parameters name – the optional name of the filter, otherwise the function name will be used.
template_folder = None Location of the template files to be added to the template lookup. None if templates should not be added. template_global(name=None) A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:
@app.template_global() def double(n): return 2 * n
New in version 0.10. Parameters name – the optional name of the global function, otherwise the function name will be used. template_test(name=None) A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:
@app.template_test() def is_prime(n): if n ==2: return True for i in range(2, int(math.ceil(math.sqrt(n)))+1): if n%i ==0: return False return True
New in version 0.10. Parameters name – the optional name of the test, otherwise the function name will be used. property templates_auto_reload Reload templates when they are changed. Used by create_jinja_environment(). This attribute can be configured with TEMPLATES_AUTO_RELOAD. If not set, it will be enabled in debug mode. New in version 1.0: This property was added but the underlying config and behavior already existed. test_cli_runner(**kwargs) Create a CLI runner for testing CLI commands. See Testing CLI Commands. Returns an instance of test_cli_runner_class, by default FlaskCliRunner. The Flask app object is passed as the first argument. New in version 1.0.
2.1. API 185 Flask Documentation (1.1.x), Release 1.1.4
test_cli_runner_class = None The CliRunner subclass, by default FlaskCliRunner that is used by test_cli_runner(). Its __init__ method should take a Flask app object as the first argument. New in version 1.0. test_client(use_cookies=True, **kwargs) Creates a test client for this application. For information about unit testing head over to Testing Flask Applications. Note that if you are testing for assertions or exceptions in your application code, you must set app. testing = True in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the testing attribute. For example:
app.testing= True client= app.test_client()
The test client can be used in a with block to defer the closing down of the context until the end of the with block. This is useful if you want to access the context locals for testing:
with app.test_client() as c: rv=c.get('/?vodka=42') assert request.args['vodka'] =='42'
Additionally, you may pass optional keyword arguments that will then be passed to the application’s test_client_class constructor. For example:
from flask.testing import FlaskClient
class CustomClient(FlaskClient): def __init__(self, *args, **kwargs): self._authentication= kwargs.pop("authentication") super(CustomClient,self).__init__( *args, **kwargs)
app.test_client_class= CustomClient client= app.test_client(authentication='Basic ....')
See FlaskClient for more information. Changed in version 0.11: Added **kwargs to support passing additional keyword arguments to the con- structor of test_client_class. New in version 0.7: The use_cookies parameter was added as well as the ability to override the client to be used by setting the test_client_class attribute. Changed in version 0.4: added support for with block usage for the client. test_client_class = None the test client that is used with when test_client is used. New in version 0.7. test_request_context(*args, **kwargs) Create a RequestContext for a WSGI environment created from the given values. This is mostly useful during testing, where you may want to run a function that uses request data without dispatching a full request. See The Request Context.
186 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
Use a with block to push the context, which will make request point at the request for the created environment.
with test_request_context(...): generate_report()
When using the shell, it may be easier to push and pop the context manually to avoid indentation.
ctx= app.test_request_context(...) ctx.push() ... ctx.pop()
Takes the same arguments as Werkzeug’s EnvironBuilder, with some defaults from the application. See the linked Werkzeug docs for most of the available arguments. Flask-specific behavior is listed here. Parameters • path – URL path being requested. • base_url – Base URL where the app is being served, which path is relative to. If not given, built from PREFERRED_URL_SCHEME, subdomain, SERVER_NAME, and APPLICATION_ROOT. • subdomain – Subdomain name to append to SERVER_NAME. • url_scheme – Scheme to use instead of PREFERRED_URL_SCHEME. • data – The request body, either as a string or a dict of form keys and values. • json – If given, this is serialized as JSON and passed as data. Also defaults content_type to application/json. • args – other positional arguments passed to EnvironBuilder. • kwargs – other keyword arguments passed to EnvironBuilder. testing The testing flag. Set this to True to enable the test mode of Flask extensions (and in the future probably also Flask itself). For example this might activate test helpers that have an additional runtime cost which should not be enabled by default. If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the default it’s implicitly enabled. This attribute can also be configured from the config with the TESTING configuration key. Defaults to False. trap_http_exception(e) Checks if an HTTP exception should be trapped or not. By default this will return False for all exceptions except for a bad request key error if TRAP_BAD_REQUEST_ERRORS is set to True. It also returns True if TRAP_HTTP_EXCEPTIONS is set to True. This is called for all HTTP exceptions raised by a view function. If it returns True for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions. Changed in version 1.0: Bad request errors are not trapped by default in debug mode. New in version 0.8. try_trigger_before_first_request_functions() Called before each request and will ensure that it triggers the before_first_request_funcs and only exactly once per application instance (which means process usually).
2.1. API 187 Flask Documentation (1.1.x), Release 1.1.4
Internal update_template_context(context) Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key. Parameters context – the context as a dictionary that is updated in place to add extra vari- ables. url_build_error_handlers = None A list of functions that are called when url_for() raises a BuildError. Each function registered here is called with error, endpoint and values. If a function returns None or raises a BuildError the next function is tried. New in version 0.9. url_default_functions = None A dictionary with lists of functions that can be used as URL value preprocessors. The key None here is used for application wide callbacks, otherwise the key is the name of the blueprint. Each of these functions has the chance to modify the dictionary of URL values before they are used as the keyword arguments of the view function. For each function registered this one should also provide a url_defaults() function that adds the parameters automatically again that were removed that way. New in version 0.7. url_defaults(f ) Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place. url_map = None The Map for this instance. You can use this to change the routing converters after the class was created but before any routes are connected. Example:
from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter): def to_python(self, value): return value.split(',') def to_url(self, values): return ','.join(super(ListConverter, self).to_url(value) for value in values)
app= Flask(__name__) app.url_map.converters['list']= ListConverter
url_map_class alias of werkzeug.routing.Map url_rule_class alias of werkzeug.routing.Rule url_value_preprocessor(f ) Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request() functions. The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view.
188 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
The function is passed the endpoint name and values dict. The return value is ignored. url_value_preprocessors = None A dictionary with lists of functions that are called before the before_request_funcs functions. The key of the dictionary is the name of the blueprint this function is active for, or None for all requests. To register a function, use url_value_preprocessor(). New in version 0.7. use_x_sendfile Enable this if you want to use the X-Sendfile feature. Keep in mind that the server has to support this. This only affects files sent with the send_file() method. New in version 0.2. This attribute can also be configured from the config with the USE_X_SENDFILE configuration key. Defaults to False. view_functions = None A dictionary of all view functions registered. The keys will be function names which are also used to generate URLs and the values are the function objects themselves. To register a view function, use the route() decorator. wsgi_app(environ, start_response) The actual WSGI application. This is not implemented in __call__() so that middlewares can be applied without losing a reference to the app object. Instead of doing this:
app= MyMiddleware(app)
It’s a better idea to do this instead:
app.wsgi_app= MyMiddleware(app.wsgi_app)
Then you still have the original application object around and can continue to call methods on it. Changed in version 0.7: Teardown events for the request and app contexts are called even if an unhandled error occurs. Other events may not be called depending on when an error occurs during dispatch. See Callbacks and Errors. Parameters • environ – A WSGI environment. • start_response – A callable accepting a status code, a list of headers, and an optional exception context to start the response.
2.1.2 Blueprint Objects class flask.Blueprint(name, import_name, static_folder=None, static_url_path=None, tem- plate_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, cli_group=
2.1. API 189 Flask Documentation (1.1.x), Release 1.1.4
See Modular Applications with Blueprints for more information. Changed in version 1.1.0: Blueprints have a cli group to register nested CLI commands. The cli_group parameter controls the name of the group under the flask command. New in version 0.7. Parameters • name – The name of the blueprint. Will be prepended to each endpoint name. • import_name – The name of the blueprint package, usually __name__. This helps locate the root_path for the blueprint. • static_folder – A folder with static files that should be served by the blueprint’s static route. The path is relative to the blueprint’s root path. Blueprint static files are disabled by default. • static_url_path – The url to serve static files from. Defaults to static_folder. If the blueprint does not have a url_prefix, the app’s static route will take precedence, and the blueprint’s static files won’t be accessible. • template_folder – A folder with templates that should be added to the app’s template search path. The path is relative to the blueprint’s root path. Blueprint templates are disabled by default. Blueprint templates have a lower precedence than those in the app’s templates folder. • url_prefix – A path to prepend to all of the blueprint’s URLs, to make them distinct from the rest of the app’s routes. • subdomain – A subdomain that blueprint routes will match on by default. • url_defaults – A dict of default values that blueprint routes will receive by default. • root_path – By default, the blueprint will automatically this based on import_name. In certain situations this automatic detection can fail, so the path can be specified manually instead. add_app_template_filter(f, name=None) Register a custom template filter, available application wide. Like Flask.add_template_filter() but for a blueprint. Works exactly like the app_template_filter() decorator. Parameters name – the optional name of the filter, otherwise the function name will be used. add_app_template_global(f, name=None) Register a custom template global, available application wide. Like Flask. add_template_global() but for a blueprint. Works exactly like the app_template_global() decorator. New in version 0.10. Parameters name – the optional name of the global, otherwise the function name will be used. add_app_template_test(f, name=None) Register a custom template test, available application wide. Like Flask.add_template_test() but for a blueprint. Works exactly like the app_template_test() decorator. New in version 0.10. Parameters name – the optional name of the test, otherwise the function name will be used. add_url_rule(rule, endpoint=None, view_func=None, **options) Like Flask.add_url_rule() but for a blueprint. The endpoint for the url_for() function is prefixed with the name of the blueprint.
190 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
after_app_request(f ) Like Flask.after_request() but for a blueprint. Such a function is executed after each request, even if outside of the blueprint. after_request(f ) Like Flask.after_request() but for a blueprint. This function is only executed after each request that is handled by a function of that blueprint. app_context_processor(f ) Like Flask.context_processor() but for a blueprint. Such a function is executed each request, even if outside of the blueprint. app_errorhandler(code) Like Flask.errorhandler() but for a blueprint. This handler is used for all requests, even if outside of the blueprint. app_template_filter(name=None) Register a custom template filter, available application wide. Like Flask.template_filter() but for a blueprint. Parameters name – the optional name of the filter, otherwise the function name will be used. app_template_global(name=None) Register a custom template global, available application wide. Like Flask.template_global() but for a blueprint. New in version 0.10. Parameters name – the optional name of the global, otherwise the function name will be used. app_template_test(name=None) Register a custom template test, available application wide. Like Flask.template_test() but for a blueprint. New in version 0.10. Parameters name – the optional name of the test, otherwise the function name will be used. app_url_defaults(f ) Same as url_defaults() but application wide. app_url_value_preprocessor(f ) Same as url_value_preprocessor() but application wide. before_app_first_request(f ) Like Flask.before_first_request(). Such a function is executed before the first request to the application. before_app_request(f ) Like Flask.before_request(). Such a function is executed before each request, even if outside of a blueprint. before_request(f ) Like Flask.before_request() but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint. context_processor(f ) Like Flask.context_processor() but for a blueprint. This function is only executed for requests handled by a blueprint. endpoint(endpoint) Like Flask.endpoint() but for a blueprint. This does not prefix the endpoint with the blueprint
2.1. API 191 Flask Documentation (1.1.x), Release 1.1.4
name, this has to be done explicitly by the user of this method. If the endpoint is prefixed with a . it will be registered to the current blueprint, otherwise it’s an application independent endpoint. errorhandler(code_or_exception) Registers an error handler that becomes active for this blueprint only. Please be aware that routing does not happen local to a blueprint so an error handler for 404 usually is not handled by a blueprint unless it is caused inside a view function. Another special case is the 500 internal server error which is always looked up from the application. Otherwise works as the errorhandler() decorator of the Flask object. get_send_file_max_age(filename) Provides default cache_timeout for the send_file() functions. By default, this function returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. Static file functions such as send_from_directory() use this function, and send_file() calls this function on current_app when the given cache_timeout is None. If a cache_timeout is given in send_file(), that timeout is used; otherwise, this method is called. This allows subclasses to change the behavior when sending files based on the filename. For example, to set the cache timeout for .js files to 60 seconds:
class MyFlask(flask.Flask): def get_send_file_max_age(self, name): if name.lower().endswith('.js'): return 60 return flask.Flask.get_send_file_max_age(self, name)
New in version 0.9. property has_static_folder This is True if the package bound object’s container has a folder for static files. New in version 0.5. import_name = None The name of the package or module that this app belongs to. Do not change this once it is set by the constructor. jinja_loader The Jinja loader for this package bound object. New in version 0.5. json_decoder = None Blueprint local JSON decoder class to use. Set to None to use the app’s json_decoder. json_encoder = None Blueprint local JSON decoder class to use. Set to None to use the app’s json_encoder. make_setup_state(app, options, first_registration=False) Creates an instance of BlueprintSetupState() object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state. open_resource(resource, mode=’rb’) Opens a resource from the application’s resource folder. To see how this works, consider the following folder structure:
192 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
/myapplication.py /schema.sql /static /style.css /templates /layout.html /index.html
If you want to open the schema.sql file you would do the following:
with app.open_resource('schema.sql') as f: contents=f.read() do_something_with(contents)
Parameters • resource – the name of the resource. To access resources within subfolders use forward slashes as separator. • mode – Open file in this mode. Only reading is supported, valid values are “r” (or “rt”) and “rb”.
record(func) Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the make_setup_state() method. record_once(func) Works like record() but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called. register(app, options, first_registration=False) Called by Flask.register_blueprint() to register all views and callbacks registered on the blueprint with the application. Creates a BlueprintSetupState and calls each record() callback with it. Parameters • app – The application this blueprint is being registered with. • options – Keyword arguments forwarded from register_blueprint(). • first_registration – Whether this is the first time this blueprint has been regis- tered on the application. register_error_handler(code_or_exception, f ) Non-decorator version of the errorhandler() error attach function, akin to the register_error_handler() application-wide function of the Flask object but for error handlers limited to this blueprint. New in version 0.11. root_path = None Absolute path to the package on the filesystem. Used to look up resources contained in the package. route(rule, **options) Like Flask.route() but for a blueprint. The endpoint for the url_for() function is prefixed with the name of the blueprint.
2.1. API 193 Flask Documentation (1.1.x), Release 1.1.4
send_static_file(filename) Function used internally to send static files from the static folder to the browser. New in version 0.5. property static_folder The absolute path to the configured static folder. property static_url_path The URL prefix that the static route will be accessible from. If it was not configured during init, it is derived from static_folder. teardown_app_request(f ) Like Flask.teardown_request() but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint. teardown_request(f ) Like Flask.teardown_request() but for a blueprint. This function is only executed when tearing down requests handled by a function of that blueprint. Teardown request functions are executed when the request context is popped, even when no actual request was performed. template_folder = None Location of the template files to be added to the template lookup. None if templates should not be added. url_defaults(f ) Callback function for URL defaults for this blueprint. It’s called with the endpoint and values and should update the values passed in place. url_value_preprocessor(f ) Registers a function as URL value preprocessor for this blueprint. It’s called before the view functions are called and can modify the url values provided.
2.1.3 Incoming Request Data class flask.Request(environ, populate_request=True, shallow=False) The request object used by default in Flask. Remembers the matched endpoint and view arguments. It is what ends up as request. If you want to replace the request object used you can subclass this and set request_class to your subclass. The request object is a Request subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones. environ The underlying WSGI environment. path full_path script_root url base_url url_root Provides different ways to look at the current RFC 3987. Imagine your application is listening on the following application root:
194 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
http://www.example.com/myapplication
And a user requests the following URI:
http://www.example.com/myapplication/%CF%80/page.html?x=y
In this case the values of the above mentioned attributes would be the following:
path u'//page.html' full_path u'//page.html?x=y' script_root u'/myapplication' base_url u'http://www.example.com/myapplication//page.html' url u'http://www.example.com/myapplication//page.html?x=y' url_root u'http://www.example.com/myapplication/'
property accept_charsets List of charsets this client supports as CharsetAccept object. property accept_encodings List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at accept_charset. property accept_languages List of languages this client accepts as LanguageAccept object. property accept_mimetypes List of mimetypes this client supports as MIMEAccept object. access_control_request_headers Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed. access_control_request_method Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed. property access_route If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server. classmethod application(f ) Decorate a function as responder that accepts the request as the last argument. This works like the responder() decorator but the function is passed the request object as the last argument and the re- quest object will be closed automatically:
@Request.application def my_wsgi_app(request): return Response('Hello World!')
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing. Parameters f – the WSGI callable to decorate Returns a new WSGI callable property args The parsed URL parameters (the part in the URL after the question mark).
2.1. API 195 Flask Documentation (1.1.x), Release 1.1.4
By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important. property authorization The Authorization object in parsed form. property base_url Like url but without the querystring See also: trusted_hosts. property blueprint The name of the current blueprint property cache_control A RequestCacheControl object for the incoming cache control headers. close() Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. New in version 0.9. content_encoding The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field. New in version 0.9. property content_length The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET. content_md5 The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.) New in version 0.9. content_type The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET. property cookies A dict with the contents of all cookies transmitted with the request. property data Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle. date The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822. dict_storage_class alias of werkzeug.datastructures.ImmutableMultiDict property endpoint The endpoint that matched the request. This in combination with view_args can be used to reconstruct the same or a modified URL. If an exception happened when matching, this will be None.
196 Chapter 2. API Reference Flask Documentation (1.1.x), Release 1.1.4
property files MultiDict object containing all uploaded files. Each key in files is the name from the . Each value in files is a Werkzeug FileStorage object. It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem. Note that files will only contain data if the request method was POST, PUT or PATCH and the